Tuesday 18 March 2014

Methods in Set Interface

int size():
Returns the number of elements in the set, If this set contains more than Integer.MAX_VALUE elements, returns Integer.MAX_VALUE.

Example

import java.util.*;
public class SetSize {
    public static void main(String args[]){
        Set<Integer> mySet = new HashSet<> ();
        
        System.out.println("Number Of Elements in mySet is " + mySet.size());
        
        /*Adding Elements to mySet */
        mySet.add(-1);
        mySet.add(null);
        mySet.add(-10);
        
        System.out.println("Number Of Elements in mySet is " + mySet.size());       
    }
}

Output


Number Of Elements in mySet is 0
Number Of Elements in mySet is 3

As you observe the above program, set can able to add null to it.

boolean isEmpty():
Returns true, if the set contains no elements else return false.

import java.util.*;

/* Program to check whether given set is empty or not */
public class SetEmpty {
    public static void main(String args[]){
        Set<String> mySet = new HashSet<> ();
       
        System.out.println("Is the set Empty " + mySet.isEmpty());
        
        /* Add Elements to the Set */
        mySet.add("Hi");
        mySet.add("Hello");
        
         System.out.println("Is the set Empty " + mySet.isEmpty());
    }
}

Output


Is the set Empty true
Is the set Empty false



Prevoius                                                 Next                                                 Home

No comments:

Post a Comment