Reputation: 139
When we override the equals()
method in Java, I know that Object
needs to be a parameter, but I wonder - why Object
?.
Second, let us say we override hashcode()
and implement equals()
, but set the parameter in equals()
to MyClass
instead of Object
(MyClass
being the class whose equals()
method we override). Will we still get the expected behavior if we use HashMap
?
Update: Yes, it will be overloading instead of overriding. But what will happen if we use HashMap
with overloaded equals()
? Also, I don't find the answer in related posts. Or is it something obvious that I am missing?
Upvotes: 0
Views: 128
Reputation: 393781
If you write an equals() method whose parameter is not Object, you are overloading the method, not overriding it.
Now, as for HashMap
- HashMap
calls equals to compare keys. The type of the compared keys is Object
. Therefore, if you define an equals()
method with a parameter whose not Object
, this method will be ignored by HashMap
.
I tried the following code :
public class SomeClass
{
int privateMember;
// note it's important to override hashCode, since if the hashCode of two
// keys is not the same, equals() won't be called at all
public int hashCode ()
{
return privateMember;
}
public boolean equals (Object other)
{
if (other instanceof SomeClass) {
return this.privateMember==((SomeClass)other).privateMember;
}
else {
return false;
}
}
public static void main(String[] args)
{
HashMap<SomeClass,String> map = new HashMap<SomeClass,String>();
SomeClass s1 = new SomeClass ();
SomeClass s2 = new SomeClass ();
s1.priv=4;
s2.priv=4;
map.put (s1, "something");
if (map.containsKey (s2)) {
System.out.println ("found!");
} else {
System.out.println ("not found!");
}
}
}
This code outputs "found!".
Now, if you run the exact same code, but replace the equals
method with :
public boolean equals (SomeClass other)
{
if (other instanceof SomeClass) {
return this.privateMember==((SomeClass)other).privateMember;
}
else {
return false;
}
}
The output will be "not found!", which means our equals
method was ignored.
Upvotes: 2
Reputation: 5443
The collections use the equals and hashcode methods from the Object base class. Therefore you must override them in order for your custom class to provide an implementation. You can overload equals if you wish, and that would work for situations where some code knows that it's dealing with an instance of MyClass
. However, this would be misleading.
All the collections classes are designed to work with instances of Object and Object provides a general purpose equals method.
You shouldn't really need to write an equals method directly. You can either generate one using your IDE, or use EqualsBuilder from Apache Commons (https://commons.apache.org/proper/commons-lang/javadocs/api-3.1/org/apache/commons/lang3/builder/EqualsBuilder.html) to help put it all together.
Upvotes: 0