Reputation: 2101
In eclipse's auto generated equals method, the first line compares reference equality
if(this == obj) return true;
As far as I know == is not really an equality check, it only checks if 2 references point to the same memory location. So why is it used?
Upvotes: 0
Views: 874
Reputation: 4010
It's incredibly fast to check reference equality, so they might as well get it out of the way before moving on to more aggressive comparisons.
Upvotes: 1
Reputation: 279910
Say you have two references
Foo foo = new Foo("some value", " many parameter", 1, 2, 3, 5);
Foo foo2 = foo;
if (foo2.equals(foo))
// do something
Where Foo
is a class with a bunch of fields that all need to be equal for object equality.
Comparing for reference equality early on saves you from having to check each field on the referenced objects because they are guaranteed to be equal.
Upvotes: 3