Relationship:
Note:
- All the interfaces and classes defined in the Java Collections Framework are grouped in the java.util package.
- All the concrete classes in the Java Collections Framework implement the Cloneable and Serializable interfaces. Thus their instances can be cloned and serialized.
Collection Interface
Sets
Set contains no duplicate elements.
AbstractSet
The AbstractSet class provides concrete implementations for the equals
method and the hashCode
method. The hash code of a set is the sum of the hash codes of all the elements in the set. Since the size
method and iterator
method are not implemented in the AbstractSet class, AbstractSet is an abstract class.
HashSet
The HashSet class is a concrete class that implements Set.A HashSet can be used to store duplicate-free elements. For efficiency, objects added to a hash set need to implement the hashCode method in a manner that properly disperses the hash code. Most of the classes in the Java API implement the hashCode method. For example, the hashCode in the Integer class returns its int value. The hashCode in the Character class returns the Unicode of the character. The hashCode in the String class returns s0*31n–1 + s1* 31n–2 + … + sn–1, where si is s.charAt(i).
LinkedHashSet
LinkedHashSet was added in JDK 1.4. It extends HashSet with a linked list implementation that supports an ordering of the elements in the set. The elements in a HashSet are not ordered, but the elements in a LinkedHashSet can be retrieved in the order in which they were inserted into the set. A LinkedHashSet can be created by using its no-arg constructor.
TreeSet
SortedSet is a subinterface of Set, which guarantees that the elements in the set are sorted. Additionally, it provides the methods first() and last() for returning the first and last elements in the set, and headSet(toElement) and tailSet(fromElement) for returning a portion of the set whose elements are less than toElement and greater than fromElement.
TreeSet is a concrete class that implements the SortedSet interface. To create a TreeSet, use its no-arg constructor or use new TreeSet(Collection). You can add objects into a tree set as long as they can be compared with each other. There are two ways to compare objects.