Collection Framework - HashSet And LinkedHashSet class

As ArrayLists use arrays as the underlying storage, in case of HashSet, hashtable is the datastructure that was implemented.

HashSet stores objects based on their hashcodes. Duplicates are not allowed and since its stored based on hashcode, insertion order is not preserved.

Hashing data structures comes with a initial capacity of 16  i.e. 2 power 4. There is one more terminology with regards to hashing data structures, load factor, i.e. when should a new hashset be created with double the capacity. Default load factor is 0.75 i.e. when 75% hashset is filled, a new larger hashset is created.

HashSet comes with the following constructors :

HashSet() - creates a hash set with a default initial capacity of 16 and load factor 0.75

HashSet(int initialCapacity) - creates a hash set with the specified initial capacity and load factor 0.75.

HashSet(int initialCapacity, int loadFactor) - creates a hash set with the specified initial capacity and the specified load factor

HashSet(Collection coll) - creates a hash set from the collection object.

An example of HashSet can be found  here

Now, if we have a requirement to store unique elements alongwith preserving the insertion order, then we use a LinkedHashSet.

A linked hash set is implemented with underlying data structures being linkedlist and hashtable.

All the other properties, constructors, methods remain same as Set.

An example of LinkedHashSet can be found here

Notice the difference in the outputs of the examples in this post and you will figure out how both the classes work in a slightly different manner.

Comments

Popular posts from this blog

Collection Framework - Cursors in Java

Hashed data structures