Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are there two kinds of equals() method

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!

like image 330
andyqee Avatar asked Oct 16 '12 05:10

andyqee


People also ask

What is equals () method in Java?

The equals() method compares two strings, and returns true if the strings are equal, and false if not.

What is the difference between equals () method and ==?

In simple words, == checks if both objects point to the same memory location whereas . equals() evaluates to the comparison of values in the objects.

What is equals () used for?

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.

Does equals () method and == do the same thing in Java?

== is a reference comparison, i.e. both objects point to the same memory location. . equals() evaluates to the comparison of values in the objects.


2 Answers

There is actually a good reason for this:

  • You need the equals(Object) method to override the superclass equals method in java.lang.Object
  • You often also want an overloaded 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.
  • Finally you may want to implement equals in a special way for testing with equality with objects that aren't themselves an instance of Bigram. This should be used with care (do you really want something that is not a Bigram instance to be considered equal to a Bigram?), but it does have some valid applications (e.g. comparing the contents of different types of collection objects).

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!).

like image 159
mikera Avatar answered Oct 07 '22 14:10

mikera


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).

like image 31
Vikdor Avatar answered Oct 07 '22 14:10

Vikdor