Tuesday, November 6, 2012

isEmpty method of Collection interface in java

/*
   isEmpty() method is defined as - boolean isEmpty() in Collection interface
*/
import java.util.*;
public class isEmpty {

    public static void main(String[] args) {
       
        ArrayList a1 = new ArrayList();
        a1.add("One");
        a1.add("Two");
        a1.add("Three");   
       
        boolean removeCheck;
        removeCheck = a1.remove(a1);
        removeCheck = a1.remove(a1);
        //.....
       
        System.out.println("The ArrayList on performing the a1.remove(a1) method) " + a1.isEmpty());
        for(int i=0;i<a1.size();i++)
        {
            System.out.println("The ArrayList elements (after the remove() method) are " + a1.get(i));
        }
        /*
        because a1.remove(a1) tries to remove the entire elements present in a1 but since boolean 
        remove(Object obj) is intended to remove only one instance object from the invoking  
        collection something like this...below would be the correct code
        */
        removeCheck = a1.remove(a1.get(0));
        removeCheck = a1.remove(a1.get(1));
        for(int i=0;i<a1.size();i++)
        {       
            System.out.println("\n The ArrayList will now decrease (after performing the remove(a1.get(i)) method) " + a1.get(i) + "\n");
        }
       
        a1.add("Four");
        a1.add("Five");
        a1.add("Six");       
        removeCheck = a1.removeAll(a1);
        System.out.println("The ArrayList should be empty (after removeAll() method) " + a1.isEmpty() + " as the size is now " +a1.size() + "\n");
       
        //The below does not gets displayed because the
        for(int i=0;i<a1.size();i++)
        {
            System.out.println("The ArrayList elements (after the removeAll() method) are" + a1.get(i));
        }       
               
    }

}

Answer
--------
The ArrayList on performing the a1.remove(a1) method) false
The ArrayList elements (after the remove() method) are One
The ArrayList elements (after the remove() method) are Two
The ArrayList elements (after the remove() method) are Three

The ArrayList will now decrease (after performing the remove(a1.get(i)) method) Two

The ArrayList should be empty (after removeAll() method) true as the size is now 0

No comments:

Post a Comment