Menu
Topics Index
...
`

Set Interface - Java Example Program


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());    
    }
}
OUTPUT

Set 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

DESCRIPTION

In 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.
  • Copy paste this set
    Set<String> s = new HashSet<String>();
    s.add("Seeta");
    s.add("Geeta");
    s.add("Reeta");
    s.add("Meena");
    s.add("Geeta");// Duplicate
    s.add("Reeta");// Duplicate
    in place of Integer Set and see the output.

© meritcampus 2019

All Rights Reserved.

Open In App