Item 클래스의 객체 두 개의 설명(description)과 가격(price)이 일치할 때 이 둘을 같은 것으로 본다고 하자. 다음은 이 조건으로 equals 메서드를 구현하는 방법이다.
public class Item {
private String description;
private double price;
...
public boolean equals(Object otherObject) {
// 두 객체가 동일한지 알아보는 빠른 검사다.
if (this = = otherObject) return true;
// 매개변수가 null이면 false를 반환해야 한다.
if (otherObject = = null) return false;
// otherObject가 Item의 인스턴스인지 검사한다.
if (getClass() != otherObject.getClass()) return false;
// 인스턴스 변수들의 값이 동일한지 검사한다.
Item other = (Item) otherObject;
return Objects.equals(description, other.description)
&& price = = other.price;
}
public int hashCode() { ... } // 4.2.3 hashCode 메서드 참고
}