Sunday, October 21, 2012

equals method of collection in java

import java.util.ArrayList;

public class equalsMethod {
    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;
       
        for(int i=0;i<a1.size();i++)
        {

            /*
               equals method of collection checks whether the index of one collection object has the 
               same value as the corresponding index of the other collection object.Here it checks for 
               whether a1.get(1) equals a2.get(1), a1.get(2) equals a2.get(2) or not...correspondingly 
               etc...
            */
            result = a1.get(i).equals(a2.get(i));
            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 ? false
a2's Four and a1's Four are equal ? true

a2's 5 and a1's Five are equal ? false 

No comments:

Post a Comment