HashSet in java


In this Collection framework tutorial we will learn what is java.util.HashSet in Collection framework in java.



Contents of page :
  • What is hierarchy of HashSet in java?
  • java.util.HashSet in java
  • Creating java.util.HashSet in java (using constructor)
  • Add element in java.util.HashSet
  • Remove element from java.util.HashSet
  • contains element in java.util.HashSet
  • Size of java.util.HashSet in java
  • Iterate over elements in java.util.HashSet using iterator() in java
  • Iterate over elements in Set using enumeration in java
  • Iterate over elements in Set using enhanced for loop
  • Some other important methods java.util.HashSet>
  • synchronizing java.util.HashSet
  • Complexity of methods in java.util.HashSet
  • Features of HashSet in java
  • When to use HashSet in java >
  • What is Load Factor in java ?



What is hierarchy of HashSet in java?
-java.lang.Object
-java.util.AbstractCollection
 -java.util.AbstractSet
  -java.util.HashSet


For more detailed hierarchy information read : Set hierarchy in java


java.util.HashSet in java
java.util.HashSet is implementation of the java.util.Set interface.
java.util.HashSet enables us to store element, it does not allow us to store duplicate elements in java.






Creating java.util.HashSet in java (using constructor)
Constructs a new set, it is internally implemented using HashMap in java.
Its initial capacity is 16. And load factor is 0.75 (We’ll discuss it later in post)

Set<String> hashSet=new HashSet<String>();
Defining HashSet<String> means set can be used to store only String types, storing any other type will cause compilation error in java.


Add element in java.util.HashSet
add(E element)
Adds specified element in HashSet if it is not already present.
hashSet.add("javaMadeSoEasy");    
Will insert “javaMadeSoEasy” in hashSet in java.



Remove element from java.util.HashSet in java
remove(Object object)
If set contains specified object, than it is removed and method returns true.
hashSet.remove("javaMadeSoEasy");
Removes first occurrence of “javaMadeSoEasy


contains element in java.util.HashSet
contains(Object object)
Method returns true if HAshSet contains specified on specified index in java.

hashSet.get(2);
Method returns element on 2nd index in java.
         

Size of java.util.HashSet
size()
Method returns size of HashSet in java.

System.out.println(hashSet.size());
will print size of hashSet in java.



Iterate over elements in java.util.HashSet using iterator() in java

iterator() method returns iterator to iterate over elements in HashSet.
Iterator important methods :
hasNext() method returns true if the iteration has more elements. (Traversing/Iteration is  done in forward direction) in java.
next() method - returns next element in iteration in java.
if the iteration has no more elements than NoSuchElementException is thrown.
remove() method - removes last element returned by iterator.
Method must always be called after call to next() method else IllegalStateException is thrown in java.

code in java-
    Iterator<String> iterator=hashSet.iterator();
   while(iterator.hasNext()){
          System.out.println(iterator.next());
   }

iterator returned by java.util.HashSet is fail-fast. Means any structural modification made to HashSet like adding or removing elements during Iteration will throw java.util.ConcurrentModificationException in java.
Few more important points about iterator >
  • Removing element by using iterator may throw IllegalStateException in java.
  • If we add some element which is already present in set than no exception is thrown because size of set remains same (it is not structural modification ) in java.

    Iterator<String> iterator=hashSet.iterator();
   while(iterator.hasNext()){
          System.out.println(iterator.next());
             hashSet.add("uk");    
   }
Element has been added (which set didn’t contained previously) during iteration which cause ConcurrentModificationException to be thrown.



Iterate over elements in Set using enumeration  in java
   Enumeration<String> listEnum=Collections.enumeration(set);   
   while(listEnum.hasMoreElements()){
      System.out.println(listEnum.nextElement());
   }
enumeration is also fail-fast.


Iterate over elements in Set using enhanced for loop in java
          for (String string : set) {
             System.out.println(string);
      }
enhanced for loop is also fail-fast in java.


Some other important methods of HashSet in java >
isEmpty() method returns true if this list contains no elements in java.

clear() method removes all elements from set in java.



synchronizing java.util.HashSet in java
We can synchronize hashSet by using Collections’s class synchronizedList method in java.
Set synchronizedSet = Collections.synchronizedSet(set);
Now, no 2 threads can access same instance of set concurrently in java.


Complexity of methods in java.util.HashSet
We will discuss about complexity of HashSet in HashMap ( because HashSet is internally implemented using HashMap.)


Features of java.util.HashSet
  1. HashSet  is implementation of the java.util.Set interface in java.

  1. HashSet is internally implemented using java.util.HashMap in java.

  1. Duplicate elements - HashSet does not allows to store duplicate elements in java.

  1. Null elements - One null element can be added in HashSet in java.
  2. Insertion order - HashSet  does not maintains insertion order in java.
Example in java-
Let’s say we add 3 elements in hashSet
hashSet.add("ind");    
hashSet.add("aus");    
hashSet.add("sa");

On displaying insertion order will not be maintained i.e.
sa
aus
ind


  1. synchronized - HashSet is not synchronized (because 2 threads on same HashSet object can access it at same time) in java.

  1. Performance - HashSet is not synchronized, hence its operations are faster as compared to some other synchronized implementation of Set interface in java.



When to use java.util.HashSet >
  1. HashSet can be used when we don’t want to store duplicate elements in java.

  1. HashSet can be used when we want to store only one null in java.

  1. We must prefer HashSet for when add and remove operations are more as compared to get operations in java, and

  1. HashSet can be used when we are not working in multithreading environment in java.



What is Load Factor in java ?
Default load factor is 0.75
That means when set will be 75% filled,  it’s capacity will be doubled.

Example in java >
Initially when number of elements is 0,  default capacity =16, Load Factor =0.75, HashSet is 0% full.

number of elements
capacity of HashMap
Load factor
HashSet filled in %age
0
16
0.75
0%
4
16
0.75
25%
8
16
0.75
50%
11
16
0.75
68.7%
When next element will be added (i.e. 12th element), hashSet will be 75% filled and capacity will be doubled i.e. from 16 to 32.
12
32
0.75
37.5%



So in this Collection framework tutorial we learned what is java.util.HashSet in Collection framework in java.


Having any doubt? or you you liked the tutorial! Please comment in below section.
Please express your love by liking JavaMadeSoEasy.com (JMSE) on facebook, following on google+ or Twitter.


RELATED LINKS>

Set hierarchy in java - Detailed - HashSet, CopyOnWriteArraySet, LinkedHashSet, TreeSet, ConcurrentSkipListSet, EnumSet classes


Set >


EnumSet in java with program


List vs Set - Similarity and Differences






HashSet - isEmpty, size and clear methods program


HashSet - iterate using iterator, Enumeration and enhanced for loop program


HashSet - fail-safe or fail-fast iteration using iterator, Enumeration and enhanced for loop program


HashSet - synchronizing using Collections.synchronizedSet program


HashSet - making set unmodifiable using Collections.unmodifiableSet





Important Similarity and Differences Collection classes in concurrent and non-concurrent packages >

TreeSet vs ConcurrentSkipListSet - Similarity and Differences with program


No comments:

Post a Comment