0

the "array1.equals(array2) compares whether array1 and array2 refer to the same array object" sentence is written in my java book but I don't understand what it means...I mean when arrays refer to same object? Thanks in advance.

Farzad
  • 113
  • 1
  • 8
  • Possibly a duplicate of: https://stackoverflow.com/questions/8777257/equals-vs-arrays-equals-in-java – Brent Writes Code Aug 20 '15 at 21:04
  • It compares whether array1 and array2 are the same references – Kristian Vukusic Aug 20 '15 at 21:05
  • https://stackoverflow.com/questions/8777257/equals-vs-arrays-equals-in-java is not duplicate, but related. That answer doesn't explain why equals work the way it does and may cause confusion by introducing other concept the op is not aware of (`Arrays.equals(a,b)`) – OscarRyz Aug 20 '15 at 21:05
  • `array1` and `array2` are *references* to an array. This function will check if those *references* are the same. If you want to check if the *contents* of the arrays are the same you can use `Arrays.equals(array1, array2);` – Peter Lawrey Aug 20 '15 at 21:23

2 Answers2

3

It means that it test if your are referring to the same object, not its contents:

class A {
    public static void main( String ... args ) {
        String [] a = { "a", "b", "c" };
        String [] b = { "a", "b", "c" };
        String [] c = a;

        System.out.println(a.equals(b));// false, same content but different object.
        System.out.println(a.equals(c));// true, they are the same object
    }
}

This is because the array in Java still inherits from java.lang.Object whose default implementation is to compare "references" to internally it is the same as

a == b;

For more on this you can see:

Community
  • 1
  • 1
OscarRyz
  • 196,001
  • 113
  • 385
  • 569
  • So if I for example change the value of c[0](in your example) after declaration a.equals(c) will return true again? – Farzad Aug 20 '15 at 21:45
  • 1
    `a.equals(c)` will still return true, yes. Changing `c[0]` will also change `a[0]`. `c` and `a` are just two names for the same array, and that is what `equals` tests. – Louis Wasserman Aug 21 '15 at 00:28
2

What you need to understand is that a variable is not the object. It is just a reference to an object. Just like a street sign is not the street itself but points to the street, so are "array1" and "array2" not arrays but references to arrays.

array1.equals(array2) checks if they both point to the same array object and thus are "equal", because they do the same.

x squared
  • 3,173
  • 1
  • 26
  • 41