Friday, 6 January 2017

HashSet in java

HashSet implements Set interface and extends AbstractSet class. It is part of java.util package.

Key feature of HashSet:

1.       HashSet contain unique elements only. If you add duplicate in it, previous value will be overwritten (see example).
2.       HashSet allows one null value only.
3.       HashSet doesn’t maintain insertion order so when you retrieve elements from it they may be returned in random order. If you want to get element in order of insertion, use LinkedHashSet.
4.       HashSet is non-Synchronized.
5.       HashSet internally uses HashTable to store the elements.

Difference

·         HashSet vs LinkedHashSet
·         HashSet vs TreeSet
·         ArrayList vs HashSet
Now let’s look at the ways in which you can create HashSet in java. Please click on each to learn the creation technique.

·         HashSet hSet = new HashSet();
·         HashSet hSet = new HashSet (Collection c);
·         HashSet hSet = new HashSet (int initialCapacity);
·         HashSet hSet = new HashSet (int initialCapacity, float LoadFactor);
Now let’s look at different ways in which you can use HashSet that we created.

HashSet operations

·         Sort the elements in HashSet (if sorting is required, better use TreeSet)
·         Search element in HashSet
·         Remove element from HashSet
·         Remove all elements from the HashSet
·         Remove element from a particular index in HashSet

Traverse LinkedList

·         Traverse HashSet using Iterator
·         Traverse HashSet using Enumeration

NoteYou cannot traverse Set with ListIterator

No comments:

Post a Comment

-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
If you are looking for a reference book on java then we recommend you to go for → Java The Complete Reference
Click on the image link below to get it now.