Java Online Compiler
Set Interface implemented classes:
Set interface is implemented in the following classes
  • HashSet
  • LinkedHashSet etc...
all the set interface implemnented classes does not allow duplicate elements.
HashSet Class
It is a predefined class in java.util package.It is uesed to manage the data very efficiently by not allowing duplication.which offers following menthods.
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 aargs[])
{
HashSetAdd d=new HashSetAdd();
d.list();
}
}

HashSet Clear Method:
It is used to remove all the elemnts.

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 aargs[])
{
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 aargs[])
{
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 aargs[])
{
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 aargs[])
{
HashSetSize d=new HashSetSize();
d.list();
}
}

Difference between List and Set ?
List Set
List interface allows duplicate elements Set interface doesnot 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