Collections and collections interfaces
Collections are objects used to group together and manipulate multiple data elements. They can dynamically grow and shrink, which is their advantage over arrays. Collections provide methods to add objects to a collection, remove objects from it, check if an object is present in it, retrieve objects from it, and iterate through it.
Collection interfaces
The inheritance hierarchy of the core collection interface is shown here:
Inheritance hierarchy of the core collection interface
Collection is the root interface, from which the Set and List interfaces extend. The Map interface does not extend the Collection interface. Also, do not confuse the Collection interface with the Collections class, which holds static utility methods for collections.
Let's analyze the basic behavior of these interfaces. The List interface represents ordered collections while Set cannot contain duplicate elements. The Map interface matches unique keys to values. SortedSet holds elements in sorted order while SortedMap orders the mapping in the sorted order of keys. The classes that implement these interfaces are listed below:
Set classes
The classes implementing the Set interface do not allow duplicate elements.
A HashSet is not ordered or sorted. This class offers constant time performance for basic operations like add and remove. TreeSet arranges the elements in ascending element order, sorted according to the natural order of the elements.
A LinkedHashSet is an ordered HashSet, which gives the elements in the order of insertion or last access. For instance:
LinkedHashSet linkSet = new LinkedHashSet();
linkSet.add("mango");
linkSet.add("apple");
linkSet.add("mango");
linkSet.add("banana");
Iterator i = linkSet.iterator();
while(i.hasNext())
System.out.print(i.next()); // Prints "mango apple banana"
No comments:
Post a Comment