HashSet and LinkedHashSet

HashSet (Since Java 1.2):

  •  HashSet is achild interface of Set.
  •  Underlying data structure is HashTable.(Internally it’s a HashMap. See HashTable code)
  •  Insertion order is not preserved.
  •  Duplicates are not allowed.
  •  Allows null element ( only one :) since set will not allow duplicates).
  •  Default initial capacity is 16.
  •  Default load factor is 0.75f.
  •  Threshold = capacity * load factor.
  •  Threshold is nothing but next size value to resize the collection.

Ex: HashSet hs = new HashSet();

It creates empty hash set with default initial capacity 16 and load factor is 0.75f.

Hash set size gets doubled (16+16=32), once the size of hash set reaches the Threshold (Here it is 12

(16*0.75=12)).

Example:

 Output:

LinkeHashSet(Since Java 1.4):

LinkedHashSet is almost same as HashSet but it has below advantages over HashSet.

  • Underlying data structure is HashTable and LinkedList.
  • Insertion of elements order is preserved.

Example:

 Output:

 

Posted in collections and tagged , , , .

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">