2

I have arrays of integers:

int[] arrA = {1,2,3,4,5,6,7,8,9};
int[] arrB1= {7,3,4,1,5,8,9,2,6};
int[] arrB2= {9,5,1,4,7,6,8,2,3};
int[] arrB3= {4,6,1,3,8,9,5,7,2};
int[] arrB4= {2,3,1,5,8,9,4,6,7};
int[] arrB5= {1,2,3,4,5,6,7,8,9};

and all the arrBs are added to the list, as follows:

List<int[]> list= new ArrayList<int[]>();

list.add(arrB1);
list.add(arrB2);
list.add(arrB3);
list.add(arrB4);
list.add(arrB5);

and I want to compare the equality of the array arrA with the list of arrays and I did it using this code:

boolean isEqual=false;
for(int index=0; index<list.size(); index++){
    if(list.get(index).equals(arrA)){
          isEqual=true;
    }
    System.out.println(isEqual);
}

I know that arrB5 is equal to arrA but why is it that I always get false? Am I doing the comparison right?

0

3 Answers 3

7

You're calling equals on arrays - which will just compare by reference, as arrays don't override equals. You want Arrays.equals(int[], int[]) to compare the values within the arrays.

(You don't need deepEquals in this case as you're dealing with int[] - and indeed calling deepEquals wouldn't compile, as an int[] isn't an Object[].)

Sign up to request clarification or add additional context in comments.

3 Comments

At first this was confusing, as I thought the whole point of equals was to test for value equality, but since arrays aren't classes in the same way most other objects are they can't really override Object.equals (which checks for reference equality), so in the end it made sense. Very counter-intuitive, however, for equals to work like that.
@ValekHalfHeart. Array is indeed a class. Just that it doesn't override equals method.
@ValekHalfHeart: Well arrays could have been implemented to override equals (and hashCode and toString) - it's just not the way the language was designed. Possibly a mistake; possibly not... but too late to change now.
2

ArrayUtils.isEquals() from Apache Commons does exactly that. It also handles multi-dimensional arrays.

You also should try Arrays.deepEquals(a, b)

Comments

0

according to java.sun.com The equals method for class Object implements the most discriminating possible equivalence relation on objects; that is, for any non-null reference values x and y, this method returns true if and only if x and y refer to the same object (x == y has the value true). It doesn't perform an intelligent comparison for most classes unless the class overrides it. It has been defined in a meaningful way for most Java core classes. If it's not defined for a (user) class, it behaves the same as ==. so try Arrays.equals(arrB5,arrA).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.