• iconJava Online Training In Andhra Pradesh and Telangana
  • icon9010519704

Opening Hours :7AM to 9PM

HashSet




Set Interface implemented classes:
Set interface is implemented in the following classes
1.HashSet
2.LinkedHashSet

all the set interface implemented classes does not allow duplicate elements.
HashSet Class
It is a predefined class in java.util package.It is used to manage the data very efficiently by not allowing duplication.which offers following methods.
HashSet ADD Method:
It is used to add the element to Set.
import java.util.*;
class HashSetAdd
{
void list()
{
HashSet<Integer> al=new HashSet<Integer>();
al.add(20);
al.add(10);
al.add(30);
al.add(40);
al.add(50);
System.out.println("The List Items Are "+al);
}
}

class Main
{
public static void main(String args[])
{
HashSetAdd d=new HashSetAdd();
d.list();
}
}
HashSet Clear Method:
It is used to remove all the elements.
import java.util.*;
class HashSetClear

{
void list()
{
HashSet<Integer> al=new HashSet<Integer>();
al.add(20);
al.add(10);
al.add(30);
al.add(40);
al.add(50);
System.out.println("The List Items Are "+al);
al.clear();
System.out.println("The List Items Are "+al);
}
}
class Main
{
public static void main(String args[])
{
HashSetClear d=new HashSetClear();
d.list();
}
}

HashSet Clone Method:
It is used to generate duplicate memory space.
import java.util.*;
class HashSetClone
{
void list()
{
HashSet<Integer> al=new HashSet<Integer>();
al.add(20);
al.add(10);
al.add(30);
al.add(40);
al.add(50);
System.out.println("The List Items Are "+al);
HashSet<Integer> al2;
al2=(HashSet) al.clone();
System.out.println("After Cloning Elements Are "+al2);
}
}

class Main
{
public static void main(String args[])
{
HashSetClone d=new HashSetClone();
d.list();
}
}

HashSet Remove Method:
It is used to remove the specified element
import java.util.*;
class HashSetRemove
{
void list()
{
HashSet<Integer> al=new HashSet<Integer>();
al.add(20);
al.add(10);
al.add(30);
al.add(40);
al.add(50);
System.out.println("The List Items Are "+al);
al.remove(50);
System.out.println("The List Items Are "+al);
}
}

class Main
{
public static void main(String args[])
{
HashSetRemove d=new HashSetRemove();
d.list();
}
}

HashSet Size Method:
It returns the number of elements of the Set.
import java.util.*;
class HashSetSize
{
void list()
{
HashSet<Integer> al=new HashSet<Integer>();
al.add(20);
al.add(10);
al.add(30);
al.add(40);
al.add(50);
System.out.println("The List Items Are "+al);

System.out.println(al.size());
}
}

class Main
{
public static void main(String args[])
{
HashSetSize d=new HashSetSize();
d.list();
}
}

Difference between List and Set ?
List interface allows duplicate elements
Set interface does not allow duplicate elements
Elements of list interface can be access using index value
Which does not allow to access the data based on the value