You have already seen the implementation and declaration of HashSet in previous tutorials. Now Let’s see the methods in HashSet in Java. Let’s start with some important examples –
How to create HashSet object in Java
Same like ArrayList in Java and LinkedList in Java, We can create the object of HashSet in Java. Only one thing is, In HashSet, we can specify initialCapacity and load factor to prevent unnecessary resizing of HashSet.
HashSet assetSet = new HashSet(); //HashSet instance without any element
HashSet properSet = new HashSet(50); //HashSet with initial capacity
How to store Object into HashSet
Same like ArrayList and LinkedList, We can add elements in HashSet using add() method. The only difference is, we can insert the duplicate elements.
How to check HashSet is empty
We can use isEmpty() method of Java HashSet to check whether hashSet is empty. isEmpty() method returns true if this hashSet contains no elements. You can also use size() method of Set to check if Set is empty or not. If returned size is zero then hashSet is empty.
boolean result = hSet.isEmpty(); //isEmpty() will return true if List is empty
How to remove objects from HashSet in Java
Like ArrayList, we can use remove() method to remove the element from the HashSet.
How to remove All objects from HashSet in Java
Like ArrayList, we can use clear() method to remove all element from the HashSet.
These all are the Basic operation, We can perform on the HashSet. If you have any query or need any help, please write us we will our best to resolve your doubts.