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!
The equals() method compares two strings, and returns true if the strings are equal, and false if not.
In simple words, == checks if both objects point to the same memory location whereas . equals() evaluates to the comparison of values in the objects.
Equals() is considered as a method in Java. 2. It is majorly used to compare the reference values and objects. It is used to compare the actual content of the object.
== is a reference comparison, i.e. both objects point to the same memory location. . equals() evaluates to the comparison of values in the objects.
There is actually a good reason for this:
equals(Object)
method to override the superclass equals method in java.lang.Object
equals(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.:
public boolean equals(Bigram b) {
return b.first == first && b.second == second;
}
@Override public boolean equals(Object o) {
if (!(o instanceof Bigram)) return false;
return equals((Bigram)o);
}
This way is more concise and means that you only need to implement the equality testing logic once (Don't Repeat Yourself!).
The frameworks / APIs that call equals()
method (like containsKey()
in maps, contains()
in Lists etc.,) call the overridden equals()
from the Object class and not the overloaded version. Hence you need to define the public boolean equals(Object obj)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With