There are two kinds equals methods?
public boolean equals(Bigram b) {
return b.first == first && b.second == second;
}
@Override public boolean equals(Object o) {
if (!(o instanceof Bigram))
return false;
Bigram b = (Bigram) o;
return b.first == first && b.second == second;
}
compare with the 2 methods,when we want to override the equal method,why we need to define an equals method whose parameter is of type Object!
There is actually a good reason for this:
equals(Object)method to override the superclass equals method injava.lang.Objectequals(Bigram)method that handles the case where the compiler can prove that the type is Bigram at compile time. This improves performance by avoiding type checking/casting and gives you better type checking in your code.Normally however it is best to implement them so that one method calls the other, e.g.:
This way is more concise and means that you only need to implement the equality testing logic once (Don’t Repeat Yourself!).