Erik
Erik

Reputation: 503

How does an array's equal method work?

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);

Upvotes: 5

Views: 4596

Answers (5)

Platinum Azure
Platinum Azure

Reputation: 46203

You are correct that the == operator only compares for reference equality, so the second and third print statements do what you expect.

The .equals method might compare by some other means than reference equality, but that requires the class definition to actually implement that method. If .equals is not implemented in the array class, then the runtime will fall back on Object#equals, which is the same reference equality that you find with the == operator.

In other words, it seems that either there is no .equals method in the backing class for arrays, or it is implemented differently than element-by-element comparison.

Upvotes: 1

Goran Jovic
Goran Jovic

Reputation: 9508

Arrays implicitly extend Object class. So, your equals method is inherited from there. The default implementation of equals method just checks the identity equality, i.e. is the same as ==.

Upvotes: 1

Sean Patrick Floyd
Sean Patrick Floyd

Reputation: 299138

An Array is an Object and it doesn't override Object.equals(), so the standard implementation of Object.equals() applies. array.equals(something) is true if and only if array == something.

Upvotes: 1

Hot Licks
Hot Licks

Reputation: 47749

Plain Java arrays (ie, not ArrayList or some such) do not, themselves, implement equals, but rather use the implementation in Object. This is basically just an address compare.

(But note that java.util.Arrays implements some static equals methods for generic arrays.)

Upvotes: 3

Jon Skeet
Jon Skeet

Reputation: 1503040

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.

Upvotes: 16

Related Questions