Hash

5BRack·2022년 7월 4일

자바란?

목록 보기
29/42

Hash 란?

  • 객체의 해시코드는 객체가 저장된 번지와 연관된 값
  • 객체가 저장된 번지를 기준으로 생성된 정수형 고윳값

class A{}
public class Test {

    public static void main(String[] args) {
        A a = new A();
        System.out.printf("%x",a.hashCode());
    }
    
            
}
  • Object 객체의 hashCode()메서드로 hash 값 호출

Objects.hash() 메서드를 이용한 해시코드 생성

System.out.println(Objects.hash(1,2,3));

hash의 중복확인 매커니즘

  1. hashcode() 가 동일한지 확인
  2. equal() 결과가 true 인지 확인
  • 1,2 단계 통과시 동일한 객체로 인식
  • 그 외는 다른 객체로 인식
  • 1단계 hashcode값이 다를 때 2단계는 검사하지 않는다

클래스내에서 hashCode,equals를 오버라이딩을 하여 hash값을 맞춰줄 수 있다.

class A{
    int data;
    public A(int data){
        this.data = data;
    }

    @Override
    public boolean equals(Object obj) {
        if(obj instanceof A){
           this.data = ((A)obj).data;
           return ture;
        }
        return false;
    }

    @Override
    public int hashCode() {
        return Objects.hash(data);
    }
}

0개의 댓글