The
Set
interface contains only methods inherited from
Collection
and adds the restriction that duplicate elements are prohibited. Two
Set
instances are equal if they contain the same elements. As implied by its name, this interface models the mathematical set abstraction.
Set Interface Methods:
Set Interface
import java.util.*;
class SetTest
{
public static void main(String arg[])
{
Set<Integer> s = new HashSet<Integer>();
s.add(10);
s.add(30);
s.add(98);
s.add(80);
s.add(99);
s.add(80); // Duplicate
System.out.println("Set elements : " + s);
System.out.print("Iterating set elements : ");
Iterator it = s.iterator();
while (it.hasNext()) {
System.out.print(it.next() + " ");
}
System.out.println();
System.out.println("Size of Set is : " + s.size());
System.out.println("Set contains element : " + s.contains(30));
System.out.println("Set is empty : " + s.isEmpty());
}
}
OUTPUTSet elements : [98, 99, 80, 10, 30]
Iterating set elements : 98 99 80 10 30
Size of Set is : 5
Set contains element : true
Set is empty : false
DESCRIPTIONIn this program, a HashSet
is assigned to Set object, six elements are added to it in which one is duplicate and then set methods like Iterator
, size
, contains
and isEmpty
are applied.
THINGS TO TRY
- Add
30
to the set, the output do not differ. It do not take any duplicates.
- Add
50
to the set and see the output difference, where 50
will be added to set and the size of set will be increased by 1
.