Reputation: 217
I understood the purpose of overriding the equals() method and hashCode() method. But my question can we override hashcode and equals in non-hash collection like ArrayList?
Upvotes: 0
Views: 101
Reputation: 12665
The methods equals()
and hashCode()
are declared in Object
(the parent of everything in Java), so technically yes, you can override them from any class.
As for the "sense" of doing it, that's up to you.
Why do you override them usually? Because you want two objects that are technically two different instances, but functionally the same instance, to be hashed the same way in a hash implementation (for example the HashMap
).
Take this for example:
public class Id {
private final String id;
public Id(String id) {
this.id = id;
}
}
If you do the following:
Id id1 = new Id("1");
Id id2 = new Id("1");
id1.equals(id2); //<-- false
... you get false
by comparing them because they are not the same instance.
Hence, if you were to use them into a key of an hash map, then the two objects would generate two different hashes and for that, would be treated as two separate keys.
However, for you the fact that the string 1
is the same in both may mean they are the same thing and should be considered as the same key.
So you override equals()
and hashCode()
accordingly.
If you need the same to be done on any kind of object (including ArrayList
), then yes it makes sense
(Note: you usually need this when you need to use these objects as key of an hash - like an HashMap
).
If you don't, then no it's not required.
As a side note, ArrayList
is not a modifiable class so even if you wanted, you couldn't change the implementation of equals()
and hashCode()
.
What you may do though, is to wrap that list inside a class of your and then implement the methods as you wish.
Upvotes: 2