Home  >  Article  >  Java  >  Override equals method

Override equals method

巴扎黑
巴扎黑Original
2017-07-20 16:46:171967browse

Override equals(Object obj) method

equals() method is one of the basic methods implemented in the Object base class and is used to customize the equality rules of objects.

#You can use == and equals() when comparing two objects. == is used to compare whether the reference addresses of two objects are equal, while the equals() method is mainly used to compare whether the contents of two objects are equal.

The equals() method has been defined in Object, but this method is directly implemented using the == operator. Therefore, if the subclass does not override this method, then the subclass object will use Object when comparing. The result of equals() defined in is the same as the comparison result of the == operator.

#Object class equals() method in


  1. ##
    public boolean equals(Object obj) {return (this == obj);
    }
2. Custom euqals() method

public boolean equals(Object obj) {if (this == obj) return true;if(obj != null && obj.getClass() == Person.class) {// 此处,使用 obj.getClass() == Person.class 来确定类型相同时,才进行判等Person p = (Person) obj;// 接下来是内容判断// ...}
}

The above is the detailed content of Override equals method. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn