Sunday, April 17, 2011

How to compare value in array?

Hi, how to compare value in an array?

I have array named list which contains 12 elements. I see if value in index 0 is equal or not equal to value in index 2.

I have tried this code but it doesnt seems to work.

if ((list.get(0)==list.get(2) && list.get(1)==list.get(3)) 
{
   System.out.println("equal")
}
From stackoverflow
  • If it's really an array, you want:

    if (list[0] == list[2] && list[1] == list[3])
    

    Note that if the array is of reference types, that's comparing by reference identity rather than for equality. You might want:

    if (list[0].equals(list[2])) && list[1].equals(list[3]))
    

    Although that will then go bang if any of the values is null. You might want a helper method to cope with this:

    public static objectsEqual(Object o1, Object o2)
    {
        if (o1 == o2)
        {
            return true;
        }
        if (o1 == null || o2 == null)
        {
            return false;
        }
        return o1.equals(o2);
    }
    

    Then:

    if (objectsEqual(list[0], list[2]) && objectsEqual(list[1], list[3]))
    

    If you've really got an ArrayList instead of an array then all of the above still holds, just using list.get(x) instead of list[x] in each place.

    Jessy : Thanks Jon. Thats really help. but how if instead of looking for equality, I wanted to check if the elements is not equal? can I just use if (! (objectsEqual(list[0], list[2]) && objectsEqual(list[1], list[3])))
  • You are comparing object references, not objects themselves. You need to use a method call. All classes inherit equals() from the root Object class, so it might work:

    if(list.get(0).equals(list.get(2)) && list.get(1).equals(list.get(3)))
    {
       System.out.println("equal");
    }
    

    This article seems to be a good summary of other comparison methods available.

  • if(list[0] == list[2] && list[1] == list[3]){
        System.out.println("equal");
    }
    

    If they are strings:

    if(list[0].equals(list[2]) && list[1].equals(list[3])){
        System.out.println("equal");
    }
    

0 comments:

Post a Comment