Header Ads

Header ADS

2.2:set interface

 import java.util.HashSet;

import java.util.Set;


public class SetExample {

    public static void main(String[] args) {

        // Create a Set of integers using HashSet

        Set<Integer> mySet = new HashSet<>();


        // Add elements to the set

        mySet.add(5);

        mySet.add(10);

        mySet.add(15);

        mySet.add(20);

        mySet.add(25);


        // Add a duplicate element (it will be ignored)

        mySet.add(10);


        // Iterate and print elements

        System.out.println("Set elements:");

        for (Integer num : mySet) {

            System.out.println(num);

        }


        // Check if an element exists in the set

        boolean contains15 = mySet.contains(15);

        System.out.println("Contains 15? " + contains15); // Output: true


        // Get the size of the set

        int size = mySet.size();

        System.out.println("Set size: " + size); // Output: 5


        // Remove an element

        mySet.remove(20);


        // Check if the set is empty

        boolean isEmpty = mySet.isEmpty();

        System.out.println("Is the set empty? " + isEmpty); // Output: false

    }

}


No comments

Powered by Blogger.