2

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?

2
  • 1
    Welcome! What have you tried so far? Commented Jun 21, 2012 at 14:45
  • Are you storing complex objects in the array? Commented Jun 21, 2012 at 14:47

2 Answers 2

2

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.

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

Comments

1

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

1 Comment

Nowhere does the OP mention using the Apache Commons libraries.

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.