이글루스 | 로그인  



hashCode() 함수

java에서 equals() 메소드를 오버라이드 할 경우 반드시 hashCode 메소드도 같이 오버라이드 해 줘야 한다.
그렇게 해 주지 않을 경우
예를 들어

equals() 메소드를 확장한 PhoneNumber class 를
Map m = new HashMap()
m.put(new PhoneNumber(a,b,c), "jenny")
를 한후

m.get(new PhoneNumber(a,b,c)) 를 할 경우 jenny가 나올거라 예상 되지만 실제로는 null 가 나온다.
이건 PhoneNumber 클래스가 입, 출력시 서로 다른 hashCode를 가지기 대문이라고 한다.
그래서 get, put 메소드가 서로 다른 bucket와 hasBucket에서 검색을 하기 때문이란다.

hashCode 메소드를 작성 하는 방법

1 int result 에 0 이 아닌 정수를 보존 한다.
  int result  = 17;
2 equals 메소드 안에서 사용되어 지는 field 에 대해서 다음의 실행한다.
  - boolean 타입의 경우 f ? 0 : 1


----- 생략 -----
이렇게 하는 것보다.. 이 방법으로 제공 되는 라이브러리가 있다.

org.apache.commons.lang.builder.HashCodeBuilder

public class HashCodeBuilder extends Object

Assists in implementing Object.hashCode() methods.

This class enables a good hashCode method to be built for any class. It follows the rules laid out in the book Effective Java by Joshua Bloch. Writing a good hashCode method is actually quite difficult. This class aims to simplify the process.

All relevant fields from the object should be included in the hashCode method. Derived fields may be excluded. In general, any field used in the equals method must be used in the hashCode method.

To use this class write code as follows:

 public class Person {   
String name;
int age;
boolean smoker;
...

public int hashCode() {
// you pick a hard-coded, randomly chosen, non-zero, odd number
// ideally different for each class
return new HashCodeBuilder(17, 37).
    append(name).
    append(age).
    append(smoker).
    toHashCode();
}
}


위 방법으로 하면 쉽게 구할수 있다.










by 나림 | 2007/09/20 14:26 | java | 트랙백 | 덧글(0)

트랙백 주소 : http://gt1000.egloos.com/tb/773620
☞ 내 이글루에 이 글과 관련된 글 쓰기 (트랙백 보내기) [도움말]

:         :

:

비공개 덧글

◀ 이전 페이지          다음 페이지 ▶