Does the equals method work with objects? If so, how?

♀尐吖头ヾ 提交于 2019-12-01 06:05:06
Luiggi Mendoza

You're not overriding the Object#equals method, but overloading it. In your method declaration you use Animal type instead of Object:

public boolean equals(Animal other)

A good overriding of the method would be using the instanceof operator. Showing an example:

@Override
public boolean equals(Object other) {
    if(other instanceof Animal) {
        Animal otherAnimal = (Animal)other;
        //comparison logic...
    }
    return false;
}

More info on the subject:

For your question on how java knows how to compare objects, you need to override the equals method

 public boolean equals(Object other){
    // return true or false based on your logic

  }

While comparing, equals method is used. You can have a look at this good tutorial which explains the significance of the equals method.

http://www.thejavageek.com/2013/06/26/what-is-the-significance-of-equals-method-in-java/

Also, only overriding equals is not enough if you are using objects into collections those use hashing. You will find a good tutorial at

http://www.thejavageek.com/2013/06/28/significance-of-equals-and-hashcode/

Every class inherits the Object class silently. And the Object class has a equals method. So if any class doesn't override the equals method then it will use the default implementation of Object.equals.

From the doc

The equals method for class Object implements the most discriminating possible equivalence relation on objects; that is, for any non-null reference values x and y, this method returns true if and only if x and y refer to the same object (x == y has the value true).

From the source code of Object.equals

public boolean equals(Object obj) {
    return (this == obj);
}

So If any object doesn't have it's own implementation of equals then the equals method will simply check if the object reference is same or not.

So get a desired result from equals you need to implement by your own as alread suggested in other answer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!