I am confused with a comparison between aliases in Strings and aliases in Arrays.
String a = "hello";
String b = "hello";
a == b;
>>> true
int [] a = {1,2,3};
int [] b = {1,2,3};
a == b
>>> false
I knew in Strings, when you call new String method, it would direct to a different address. Otherwise, it would take the previous address with the same String literal.
However, things do not work for arrays. Can someone explain why it gives false?
Answer
As String
s are immutable, Java can perform an optimization: when it detects that the two String
s are both initialized to refer to the same value: it only needs to make a single object of that value, and can have both String
variables refer to it.
As arrays are mutable, if it were attempt to make the same optimization, a change to a
(e.g. a[1]=7
) would cause b
to change too. This behavior isn't what one would expect, so it is not done. If you explicitly wanted that behavior, you would have explicitly set b
to refer to what a
referenced (e.g. int[] b = a
).
No comments:
Post a Comment