Home > Java > javaTutorial > body text

Override equals method

巴扎黑
Release: 2017-07-20 16:46:17
Original
1972 people have browsed it

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);
    }
    Copy after login
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;// 接下来是内容判断// ...}
}
Copy after login

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

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template