In the last tutorial we learn HashSet in java ,now we will learn how to remove all elements from HashSet. And to remove all elements from Hashset we use method clear() to remove all elements.
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
public class Example1 {
public static void main(String args[]) {
// HashSet declaration
HashSet<String> hashset = getHashSet();
}
public static HashSet<String> getHashSet(){
// HashSet declaration
HashSet<String> hashset = new HashSet<String>();
// Adding elements to the HashSet
hashset.add("Item4");
hashset.add("Item2");
hashset.add("Item6");
hashset.add("Item1");
hashset.add("Item3");
hashset.add("Item5");
//Addition of duplicate elements
hashset.add("Item2");
hashset.add("Item4");
//Addition of null values
hashset.add(null);
hashset.add(null);
System.out.println("Before Remove hashSet ");
for (String temp : hashset) {
System.out.println(temp);
}
hashset.clear();
//Displaying HashSet elements
System.out.println("after remove HashSet = "+hashset );
return hashset;
}
}
//result :
Before Remove hashSet
null
Item1
Item2
Item5
Item6
Item3
Item4
after remove HashSet = []
Subscribe to:
Post Comments (Atom)
EmoticonEmoticon