Make delicious recipes!

Useful collection classes in Java

  1. HashSet<T>: HashSet provides a "Set" data-structure to eliminate duplicates.
    More accurately, if two elements have the same hashcode(), then only one of them can be stored in a HashSet.
    The iterator returned by this class iterates over the elements in no particular order.

  2. TreeSet<T>: TreeSet provides the same functionality as provided by the HashSet, except that the iterator returned by TreeSet iterates over the elements according to their natural sort-order.
    A comparator can be specified at the time of TreeSet creation to override the natural ordering of the elements.

  3. LinkedHashSet<T>: LinkedHashSet is same as HashSet, except that the iterator returned by the LinkedHashSet returns the elements in the same order as they were inserted.

  4. EnumSet<E extends Enum<E>>: An EnumSet is a Set whose keys belong to the same Enum. Enum sets are represented internally as bit vectors.
    This representation makes an EnumSet very compact and fast as compared to a normal HashSet.
    The iterator for this class traverses the elements in their natural order (the order in which the enum constants are declared).

  5. CopyOnWriteArraySet<T>: This Set is suited for multi-threaded applications where the number of read operations vastly outnumber write operations.
    This class uses an internal CopyOnWriteArrayList for all of its operations.
    Basic idea behind this class is that whenever an iterator is created, the backing array is copied over to a new location such that the new array remains unaffected by write operations to the original array.
    Thus, iterators of this class never throw ConcurrentModificationException.

  6. ConcurrentSkipListSet<T>: This Set is based on Skip Lists.
    It provides a concurrent set whose elements are kept sorted in their natural order or by a comparator provided during the time of construction of the Set.
    This set is basically a concurrent version of the TreeSet.
    The operations performed by this implementation are lock-free so that multiple threads can write to the same set at the same time.

  7. Each of the sets described above have a corresponding map class also.

Like us on Facebook to remain in touch
with the latest in technology and tutorials!

Got a thought to share or found a
bug in the code?
We'd love to hear from you:

Email: (Your email is not shared with anybody)

Facebook comments:

Site Owner: Sachin Goyal