2

Any array in java is Object. hence it has equals method. But I cannot watch realization of this method(or maybe is it possible ?)

I wrote several examples and always == and equals returns similar results.

Is there way when == and equals return different results ?

gstackoverflow
  • 36,709
  • 117
  • 359
  • 710

3 Answers3

7

There is difference

1)

int[] a1 = {};
long[] a2 = {};
boolean r1 = a1.equals(a2);  // returns false
boolean r2 = a1 == a2;       // compile time error

2)

int[] a1 = null;
int[] a2 = {};
boolean r1 = a1.equals(a2);  // throws NPE
boolean r2 = a1 == a2;       // returns false
Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
  • can you provide link where I can show in what cases I can use == operator without compilation errors ? – gstackoverflow May 22 '14 at 08:56
  • 1
    it happens when right operand cannot be cast to left operand,eg Object[] and String[] - OK. But Integer[] and String[] - error. Primitive arrays should always be same type – Evgeniy Dorofeev May 22 '14 at 09:01
  • It is not absolutely right. jls says: **The equality operators may be used to compare two operands that are convertible (§5.1.8) to numeric type, or two operands of type boolean or Boolean, or two operands that are each of either reference type or the null type. All other cases result in a compile-time error.** it is not full clear for me but it is obviously differs with your answer – gstackoverflow May 22 '14 at 10:26
2

I don't think so this is the equalsmethod :

 public boolean equals(Object obj) {
        return (this == obj);
    }

And it internally uses == operator for comparison.

You can view the javaDoc here.

Runcorn
  • 5,144
  • 5
  • 34
  • 52
0

Just write this testin a test class

@Test
public void testArray() {
     int[] A = {1,2};
     int[] B = {1,2};
     assertTrue(Arrays.equals(A, B));
     assertTrue(A.equals(B));
     assertTrue(A == B);
}

In general "==" compares the addresses while .equals() will compare using the object equals which depends on the objects (comparing to File object is different than comparing to Integers).

EDIT:

My bad, this is actually wrong, == and equals are actually the same in java as seen there: equals vs Arrays.equals in Java

In case of arrays, it is indeed the same, and quite confusing I must say. I modified my test to show the difference.

Community
  • 1
  • 1
Arnaud Potier
  • 1,750
  • 16
  • 28