arrays - Explain the clone() function in java -
the output of following codeblock 'false'. why?
byte[] = {1,2,3}; byte[] b = (byte[]) a.clone(); system.out.print(a==b);
==
identity operator in java. means, checks if 2 objects same thing. it's not logical equality, it's not containing same values. it's being same object.
in example, not same object. clone method of array creates new object, same content original. new object have same content, have own identity. it's new object, distinct original.
in contrast, equals method logical equality. is, 2 objects containing equal values. when cloning array, original , clone equal, because have same values. not identical, because have different identities. in terms of java's ==
operator , contract of equals
method:
- if 2 arrays equal, not identical
- if 2 arrays identical, equal
the importance of identity when 2 array variables have same identity (both pointing same object), modifying 1 of them appear modify both of them. when 2 arrays equal not identical, can modify 1 without affecting other: independent objects.
Comments
Post a Comment