Prime Phoenix
Prime Phoenix

Reputation: 21

Comparing arrays and comparing each element in both arrays

I'm new to java. Please help me out.

I want to compare Array objects, and each element in both arrays. So what should I use to check whether they are same or not: equals, deepEquals or compareTo?

Upvotes: 2

Views: 770

Answers (2)

Pshemo
Pshemo

Reputation: 124275

I am not sure if I understand your problem, but maybe this will help you a little.

Arrays.equals(array1, array2) is used with one dimensional arrays like int[10]. Arrays.deepEquals(array1,array2) is for one or more dimensional arrays like int[2][4]. Chose one based on how many dimensions have arrays you want to compare.

EDIT

Your code from comment doesn't compile but I'm starting to understand your problem. You need to know that arrays are objects and by default in equals(Object obj) method they return this == obj. These mean they do not compare arrays by values stored in them, but only check if reference from other object obj (other array) contains reference to the same array from you are comparing (this).

You can check it this way

Integer[] a1=new Integer[2];
Integer[] a2=new Integer[2];
for (int i=0; i<2; i++){
    a1[i]=i;
    a2[i]=a1[i];
}
System.out.println(a1.equals(a2));//false

but when I change i2 reference to point array from i1 equals will return true

a2=a1;//now my i2 reference points array from i1
System.out.println(a1.equals(a2));//true

To compare elements in arrays you need to iterate through array. You can write your own code to do it or use ready methods that will do it for you. Java provide such methods in class java.util.Arrays, but nobody stops you from using other libraries like Apache Commons -> ArrayUtils class.

Upvotes: 2

ControlAltDel
ControlAltDel

Reputation: 35106

As the api says, ArrayUtils.equals does a shallow comparison. Arrays/ArrayUtils.deepEquals does a deep comparison... << this is probably the one you want (deepEquals), unless you have a reason for only wanting shallow comparison

Upvotes: 1

Related Questions