Question about arrays in Java
Can someone explain why, A.equals(B)
is false
, when I initiate B
using int[] B = A.clone()
BUT true
if I initiate B
using int[] B = A
?
int[] A = {1, 2, 3, 4, 5};
int[] B = A;
//开发者_Go百科int[] B = A.clone();
if(A==B){//true
System.out.println("Equal");
}
if(A.equals(B)){//true
System.out.println("Equal");
}
Apparently, equals
method for arrays in Java is comparing reference equality (same as ==
).
If you clone it, you have a reference different object - the clone array. But, if you just point another reference to it it's the same.
Well if you use
int[] B = A;
then B
and A
refer to the same object, so trivially they're equal. The first comparison (==) would certainly return false between A
and A.clone()
as the values refer to different objects. It sounds like arrays don't override equals
(e.g. as ArrayList
does), hence the clone not being equal to the original under the equals
method either.
EDIT: Indeed, from the language specification section 10.7, Array Members:
All the members inherited from class Object; the only method of Object that is not inherited is its clone method.
In other words, the array overrides clone()
but not toString
/ hashCode
/ equals
.
For comparing arrays in Java, you might want to try
java.util.Arrays.equals(a,b);
If you use a == b
they should be different- this compares their memory references.
If you use a.equals(b)
, it probably inherits from Object, which simply uses ==
.
That probably explains why they made Arrays.equals() in the first place. Now why they chose a.equals(b) to not compare elements... hard to say.
Your question is answered precisely by the Javadoc for clone():
http://download.oracle.com/javase/6/docs/api/java/lang/Object.html#clone%28%29
specifically:
[ The clone() method ] Creates and returns a copy of this object. The precise meaning of "copy" may depend on the class of the object. The general intent is that, for any object x, the expression:
x.clone() != x
will be true, and that the expression:
x.clone().getClass() == x.getClass()
will be true, but these are not absolute requirements. While it is typically the case that:
x.clone().equals(x)
will be true, this is not an absolute requirement.
int[] B = A;
Makes B
point to the same object in memory as A
, so not only are they equal, they are the same.
when you assign B = A, you assign the reference to the same object. With clone() you get a copy of the object. The equality operator (==) tests if both symbols reference the same object where .equals method checks if the two objects have the same value (defined by the implementation of the class)
精彩评论