조슈아 블로흐는 효과적인 자바 말한다 :재정의 해시 코드() 메소드
당신은) (등호를 우선 모든 클래스에 해시 코드를() 재정의해야합니다. 그렇게하지 않으면 Object.hashCode()에 대한 일반 계약 을 위반하게되어 HashMap, HashSet 및 Hashtable을 포함한 모든 해시 기반 모음과 함께 이 제대로 작동하지 않게됩니다.
public class Match { private String homeTeam; private String awayTeam; public Match(String homeTeam, String awayTeam) { this.homeTeam = formatTeamName(homeTeam); this.awayTeam = formatTeamName(awayTeam); } } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Match that = (Match) o; final int threshold = 6; return (computeFuzzyScore(this.homeTeam, that.awayTeam) <= threshold || computeFuzzyScore(this.awayTeam, that.homeTeam) <= threshold) && computeFuzzyScore(this.homeTeam, that.homeTeam) > threshold && computeFuzzyScore(this.awayTeam, that.awayTeam) > threshold; } // formatTeamName(), computeFuzzyScore() have been left out for brevity. }
이러한 개체가 동일한이 방법 :
Match match0 = new Match("Man.City", "Atl.Madryt"); Match match1 = new Match("Manchester City", "Atlético Madryt");
내가 같은 값을 생성
hashCode()
메소드를 오버라이드 (override)하는 방법
내 오버라이드 (override) equals()
방법은 Match
객체를 비교하는 퍼지 점수 알고리즘을 구현 그런 물건들?
'match0'과'match'는 동일하지 않습니다. 그래서 그들은 최적으로 hashCode()를 가질 필요가 없다. 당신의'equals()'도'true'를 반환하지 않아야합니다. –
hashcode 문서에서 해시 코드는 동등한 인스턴스에 대해 동일해야하지만 다른 인스턴스에 대해서도 동일해야합니다. hashcode는'equals'에서 사용 된 변수만을 사용해야한다는 것을 의미합니다. – AxelH
아마도 'equals'와 같은 구현을 사용하는 것은 좋지 않을 것입니다. 이'equals' 구현체를 커스텀 코드에서만 사용하려고합니까, 아니면 표준 JDK 클래스가'equals' 메소드를 호출 할 것으로 기대합니까? – Eran