HashSet class is in java.util package of java. HashSet does not require any fix dimension like String array and int array. HashSet contains many useful methods. To add element in HashSet, we can use add() method of HashSet class.
To get value from HashSet, HashSet provides iterator () method and HashSet size() method. size() method returns total number of elements in HashSet.
HashSet Example
import java.util.HashSet; import java.util.Iterator; public class HashSetExample { public static void main(String[] args) { HashSet<String> hs=new HashSet<String>(); // duplicate element is not permitted hs.add("b"); hs.add("a"); hs.add("c"); hs.add("d"); hs.add("d"); Iterator it=hs.iterator(); while(it.hasNext()) { String value =(String)it.next(); System.out.println("Value :"+value); } //find size of hashSet System.out.println("Size :"+hs.size()); // Remove element from hashSet : hs.remove("d"); // To remove all object from hashSet hs.clear(); } }
Output
Value :d
Value :b
Value :c
Value :a
Size :4
Tags: Collections




Link to Us