Question about arrays in Java

Can someone explain why A.equals(B)there is falsewhen I start Busing int[] B = A.clone()BUT trueif I initiate Busing int[] B = A?

 int[] A = {1, 2, 3, 4, 5};



    int[] B = A;
    //int[] B = A.clone();

    if(A==B){//true
        System.out.println("Equal");
    }
    if(A.equals(B)){//true
        System.out.println("Equal");

    }
+3
source share
6 answers

Ok if you use

int[] B = A;

then Bthey Arelate to the same object, so they are trivially equal. The first comparison (==) will definitely return false between Aand A.clone(), since the values ​​refer to different objects. It seems that arrays are not overriding equals(for example, how ArrayList), so the clone is not equal to the original in the method equals.

EDIT: , 10.7, :

, Object; Object, , clone.

, clone(), toString/hashCode/equals.

+3

-, equals Java ( , ==).

, - . , , .

+4

Java

java.util.Arrays.equals(a,b);

a == b, - .

a.equals(b), , , Object, ==.

, , , Arrays.equals() . a.equals(b), ... .

+2

Javadoc clone():

http://download.oracle.com/javase/6/docs/api/java/lang/Object.html#clone%28%29

:

[ clone()] . "" . , x, :

 x.clone() != x

:

 x.clone().getClass() == x.getClass()

, . , :

 x.clone().equals(x)

, .

0
int[] B = A;

B , A, , .

0

when you assign B = A, you assign a reference to the same object. Using clone () you get a copy of the object. The equality operator (==) checks whether both characters refer to the same object where the .equals method checks whether both objects have the same value (defined by the class implementation)

0
source

Source: https://habr.com/ru/post/1794181/


All Articles