Java Collections
Java Collections
The Collections class is a utility class having static methods for doing operations on objects of classes
which implement the Collection interface. For example, Collections has methods for finding the max
element in a Collection.
The Collection interface defines methods common to structures which hold other objects. List and Set
are subinterfaces of Collection, and ArrayList and HashSet are examples of concrete collections.
Classes that implements Collection (I) methods, can take advantage of the static Class Collections
(C) methods.
List vs Set
List<E>:
An ordered collection (also known as a sequence). The user of this interface has
precise control over where in the list each element is inserted. The user can access
elements by their integer index (position in the list), and search for elements in the
list.
Set<E>:
List Set
Duplicates YES NO
Order ORDERED DEPENDS ON
IMPLEMENTATION
Positional Access YES NO
ArrayList vs HashSet
ArrayList HashSet
Implements List (Interface) Set (Interface)
Ordered YES (Preserve the order of the NO (Unordered)
elements)
Synchronized NO (not meant to be used in multi- NO (not meant to be used in
threading and concurrent environment) multi-threading and concurrent
environment)
Iterable YES (Iterator, ForEach) YES (Iterator, ForEach)
Fail-Fast YES (Will throw YES (Will throw
ConcurrentModificationException if is ConcurrentModificationException
modified structurally once Iterator has if is modified structurally once
been created) Iterator has been created)
Duplicates YES NO
Backed By Array HashMap
Access Index Based: You can retrieve object Object Based: Elements is
Method by index. accessed directly from the
Object Reference.
How HashSet Internally Works in Java
Not many programmer know that HashSet is internally implemented using HashMap in Java.
But, now a curious Java developer can question that, how come HashSet uses HashMap, because
you need a key value pair to use with Map, while in HashSet we only store one object.
HashMap allows duplicate values and this property is exploited while implementing HashSet in Java.
Since HashSet implements Set interface it needs to guarantee uniqueness and this is achieved by
storing elements as keys with same value always.
HashMap vs HashSet