Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Hey I'm currently studying for a java final and I am befuddled by a simple equals method.

The question given is

"Given the following array declarations, what does the following print"

and I thought it would be true, false, true however after copy and pasting the code it reveals the answer is false, false, true.

I understand that the == only works when they are the same instance of the object but I do not understand why the first on is false. I tried finding the method in the array api but could not find one with the same arguments.

Forgive me if this is obvious, I've been up late the past couple nights studying and am quite jaded on caffeine at the moment.

int[] d = { 1, 2, 3 };
int[] b = { 1, 2, 3 };
int[] c = d;
System.out.println(d.equals(b));
System.out.println(d == b);
System.out.println(d == c);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
442 views
Welcome To Ask or Share your Answers For Others

1 Answer

Basically, array types don't override equals to provide value equality... so you end up with the default implementation in Object, which is reference equality.

For value equality in arrays (i.e. equal elements in the same order), use the static methods in the Arrays class.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...