Sunday, October 21, 2012

contains method of collection in java

import java.util.*;
import java.*;

public class containsMethodOfCollection {
    public static void main(String[] args) {       

        ArrayList a1 = new ArrayList();
        a1.add("One");
        a1.add("Two");
        a1.add("Three");
        a1.add("Four");
        a1.add("Five");
               
        ArrayList a2 = new ArrayList();
        a2.add("10");
        a2.add("20");
        a2.add("Two");
        a2.add("Four");
        a2.add("5");
   
        boolean result;
        /*
           From the result you can find out that  for each a2.get(i), index it does not check with the 
           corresponding index of a1, instead a2.get(i) only checks internally that whether all the 
           components of a2 index wise internally do have an component of the same in the a1 
           arraylist or not.
        */
        for(int i=0;i<a1.size();i++)
        {
            result = a1.contains(a2.get(i));
            System.out.println("a2's "+a2.get(i)+" and a1's "+a1.get(i)+" are equal ? " +result);
        }
        /*
          containsAll returns true only when all the componenets of a1 or a2 have a corresponding 
          equal component in the other collection object, even if one component mismatches the 
          boolean returns false 
        */
        for(int i=0;i<a1.size();i++)
        {
            result = a1.containsAll(a2);
            System.out.println("a2's "+a2.get(i)+" and a1's "+a1.get(i)+" are equal ? " +result);
        }
       
    }
}

Answer : 
------------

a2's 10 and a1's One are equal ? false
a2's 20 and a1's Two are equal ? false
a2's Two and a1's Three are equal
? true
a2's Four and a1's Four are equal ? true
a2's 5 and a1's Five are equal ? false


a2's 10 and a1's One are equal ? false
a2's 20 and a1's Two are equal ? false
a2's Two and a1's Three are equal ? false
a2's Four and a1's Four are equal ? false
a2's 5 and a1's Five are equal ? false

No comments:

Post a Comment