Computer >> 컴퓨터 >  >> 프로그램 작성 >> Java

Java에서 HashMap의 내부 작업

<시간/>

'hashCode' 함수는 Java에서 객체의 해시 코드를 가져오는 데 사용됩니다. 이것은 상위 클래스 Object의 객체입니다. 객체 참조의 메모리를 정수로 반환합니다. 이것은 네이티브 함수입니다. 즉, Java의 직접적인 메서드를 사용하여 개체의 참조를 가져올 수 없습니다.

HashMap의 더 나은 성능을 위해 hashCode()를 적절하게 사용하십시오. 기본적으로 이 함수는 버킷 및 인덱스 값을 계산하는 데 사용됩니다. 다음과 같이 정의됩니다 -

public native hashCode()

'양동이'에 대해 언급했으므로 그것이 의미하는 바를 이해하는 것이 중요합니다. 노드를 저장하는 데 사용되는 요소입니다. 단일 버킷에는 2개 이상의 노드가 있을 수 있습니다. 노드는 연결 목록 데이터 구조를 사용하여 연결할 수 있습니다. 해시맵의 용량은 버킷과 로드 팩터를 사용하여 계산할 수 있습니다.

Capacity = number of buckets * load factor

'equals' 함수는 두 객체 간의 같음을 확인하는 데 사용됩니다. 또한 상위 클래스 Object에 의해 제공됩니다. 이 기능은 사용자 정의 구현을 제공하여 사용자 정의 클래스에서 재정의할 수 있습니다. 이 함수는 질문의 두 개체가 같은지 여부에 따라 true 또는 false를 반환합니다.

배열의 크기가 크지 않도록 인덱스 값을 생성하여 outOfMemoryException을 방지한다. 배열의 인덱스를 찾는 공식은 -

Index = hashCode(key) & (n-1) – Here n refers to number of buckets.

예를 들어 보겠습니다 -

예시

import java.util.HashMap;
class hash_map{
   String key;
   hash_map(String key){
      this.key = key;
   }
   @Override
   public int hashCode(){
      int hash = (int)key.charAt(0);
      System.out.println("The hash code for key : " + key + " = " + hash);
      return hash;
   }
   @Override
   public boolean equals(Object obj){
      return key.equals(((hash_map)obj).key);
   }
}
public class Demo{
   public static void main(String[] args){
      HashMap my_map = new HashMap();
      my_map.put(new hash_map("This"), 15);
      my_map.put(new hash_map("is"), 35);
      my_map.put(new hash_map("a"), 26);
      my_map.put(new hash_map("sample"), 45);
      System.out.println("The value for key 'this' is : " + my_map.get(new hash_map("This")));
      System.out.println("The value for key 'is' is: " + my_map.get(new hash_map("is")));
      System.out.println("The value for key 'a' is: " + my_map.get(new hash_map("a")));
      System.out.println("The value for key 'sample' is: " + my_map.get(new hash_map("sample")));
   }
}

출력

The hash code for key : This = 84
The hash code for key : is = 105
The hash code for key : a = 97
The hash code for key : sample = 115
The hash code for key : This = 84
The value for key 'this' is : 15
The hash code for key : is = 105
The value for key 'is' is: 35
The hash code for key : a = 97
The value for key 'a' is: 26
The hash code for key : sample = 115
The value for key 'sample' is: 45

'hash_map'이라는 클래스는 문자열과 생성자를 정의합니다. 이것은 'hashCode'라는 다른 함수에 의해 재정의됩니다. 여기서 hashmap의 키 값은 정수로 변환되어 해시 코드가 출력됩니다. 다음으로 'equals' 함수가 재정의되고 키가 해시맵의 키와 같은지 확인합니다. Demo 클래스는 HashMap의 새 인스턴스가 생성되는 주요 기능을 정의합니다. 요소는 'put' 기능을 사용하여 이 구조에 추가되고 콘솔에 인쇄됩니다.