What is HashSet | Collection in Java | Methods of HashSet | Java Programming
package collection;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
public class HashSetDemo {
public static void main(String[] args) {
/* How to declare the hashset
HashSet myset=new HashSet();
Set myset1=new HashSet();
*/
/*if we want to store only homogenous data, then use wrapper class
HashSet <Integer>myset=new <Integer>HashSet();
HashSet <String>myset1=new <String>HashSet();
*/
// Adding element in hasSet
HashSet myset=new HashSet();
myset.add(90);
myset.add(90);
myset.add(null);
myset.add(null);
System.out.println(myset); // Insertion order is not presevered, and duplicate elements are not allowed
//if we try to insert duplicate then only one single element will be stored, keep only one element
//result will be [null, 90]
//How to remove specific element: Provide the elements's value not order or index
myset.remove(null);
System.out.println(myset);
//inserting element : is not possible in hashSet, we can only add the element at the end of hashset
//access specific element: is not possible as index is not preserved. But one alternative is there
// convert Hashset into array list then access the hashset element
//Converting hashset into arrayList
ArrayList al=new ArrayList(myset);
System.out.println(al.get(0));
//Add another element in the hashSet
myset.add("Tech Bharat");
System.out.println(myset);
//read all element by looping
//Approach By normal for loop is not possible
// For each loop
for(Object x:myset)
{
System.out.println(x);
}
//Read element using iterator
Iterator <Object>it=myset.iterator();
while(it.hasNext())
{
System.out.println(it.next());
}
//Remove multiple values in Hashset is not possible in HashSet
//Clear all the element in HashSet
myset.clear();
// check whether HashSet is empty or not
System.out.println(myset.isEmpty());
//Size of hashset
System.out.println(myset.size());
}
}
Post a Comment