스터디/이펙티브 자바

[Effective Java] Item11. equals재정의시 무조건 hashCode도 재정의

📝 작성 : 2022.05.21  ⏱ 수정 : 
728x90

equals 재정의시 hashCode를 재정의하지 않으면 해당 클래스의 인스턴스를 HashMap, HashSet과 같은 컬렉션의 원소로 사용할 때 문제가 발생합니다.

논리적으로 같은 객체는 같은 해시코드를 반환해야합니다.

hashCode 재정의 방법

public class Address {
    private int zipcode;
    private String city;
    private List<String> street;

    //전형적인 hashCode메서드
    @Override
    public int hashCode() {
        int result = zipcode; //zipcode 대신 Integer.hashCode(zipcode) 사용 가능
        result = 31 * result + (city != null ? city.hashCode() : 0);
        result = 31 * result + (street != null ? street.hashCode() : 0);
        return result;
    }

    //한줄짜리 hashCode메서드, 성능이 살짝 아쉬움
    @Override
    public int hashCode() {
        return Objects.hash(zipcode, city, street);
    }

    //해시코드를 지연 초기화하는 hashCode메서드 - 스레드 안정성까지 고려해야 함!
    @Override
    public int hashCode() {
        int result = hashCode;
        if (result == 0) {
            result = zipcode; //zipcode 대신 Integer.hashCode(zipcode) 사용 가능
            result = 31 * result + (city != null ? city.hashCode() : 0);
            result = 31 * result + (street != null ? street.hashCode() : 0);
        }
        return result;
    }
}

외에 apache.commons.lang(또는 apache.commons.lang3), Guava등을 이용해 구현할 수도 있습니다.

반응형