Reputation: 25
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 arrB
s 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?
Upvotes: 2
Views: 331
Reputation: 1
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).
Upvotes: 0
Reputation: 1503489
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[]
.)
Upvotes: 7
Reputation: 1487
ArrayUtils.isEquals() from Apache Commons does exactly that. It also handles multi-dimensional arrays.
You also should try Arrays.deepEquals(a, b)
Upvotes: 2