So I'm learning Java and I'm trying to understand equals, but I 开发者_高级运维really don't understand it. So my question is: how does equals works? Thanks
equals
is a method you use to discover if two given objects are the same. The default implementation of equals for an object is: They are the same if they have the exact same reference.
Sometimes, you don't want this. Say you have a ComplexNumber
class, and two instances with value 1+i
. You don't want them not to be equal just because they are different instances. In essence, they represent the same number. In this case, you should override equals to make sure it behaves as intended.
HashMaps use info from equals to know if the key you passed is already there.
From Effective Java book:
Always override hashcode when you override equals
I'd also add to that: specially if you're using a Hashmap =)
Hashmaps uses also hashcode() to search faster for the keys, and the result for hashcode()
must be consistent with the equals
result. In other words, if x.equals(y)
, then x.hashcode() == y.hashcode()
(or you may have undefined behavior for your hashmap). You may have x and y with x.hashcode() == y.hashcode()
and !x.equals(y)
If you want a more specific answer, please make a more specific question =).
The equals method will compare values for equality.
the method equals is defined in the object class so which means that every other class can use this method to compare how it works: it will first check if its referring to its self then the haschode's of the object and if those are equal if so, it will then check each field in that object against the fields of the object you are comaparing to why you might ask co's the haschode could be the same but it can still contain other value's in the fields the odds are low but its needed to compare more in depth then.
equals()
means "meaningfully equivalent." It's not the same as ==
, which means "these are the same object." All classes have the equals()
method, inheirited from the Object
class. For example, say you write a Car
class that stores make, model and owner:
Car carOne = new Car("Buick", "LeSabre", "John Doe");
Car carTwo = carOne;
Here, equals()
and ==
will both return true, because both references point to the same car. But, for
Car carOne = new Car("Buick", "LeSabre", "John Doe");
Car carTwo = new Car("Buick", "LeSabre", "John Doe");
there are two distinct objects, so ==
returns false. However, since both cars are Buick LeSabres owned by John Doe, your equals()
should be written return true (assuming for this example that nobody owns more than one car of the same type).
Also, as Samuel pointed out, if you override equals()
, you should also override hashCode()
; the reasons for that are outside the scope of this question, and well-documented elsewhere.
精彩评论