Java HashTable Put

태량·2023년 6월 22일
0
public synchronized V put(K key, V value) {
        // Make sure the value is not null
        if (value == null) {
            throw new NullPointerException();
        }

        // Makes sure the key is not already in the hashtable.
        Entry<?,?> tab[] = table;
        int hash = key.hashCode();
        int index = (hash & 0x7FFFFFFF) % tab.length;
        @SuppressWarnings("unchecked")
        Entry<K,V> entry = (Entry<K,V>)tab[index];
        for(; entry != null ; entry = entry.next) {
            if ((entry.hash == hash) && entry.key.equals(key)) {
                V old = entry.value;
                entry.value = value;
                return old;
            }
        }

        addEntry(hash, key, value, index);
        return null;
    }

Java에 HashTable 클래스에 put 메소드다. 이중에 hashCode 메소드를 통해 얻은 hash 값을 16진수로 비트 연산을 하는 것에 대한 글이다.

  1. 비트 연산이란 무엇인가?
  • 바이너리 데이터에 대한 연산. 위의 연산자 &는 두 비트가 모두 1일 때 1이며 다른 경우는 모두 0으로 연산 된다.
  1. 0x7FFFFFFF을 2진수로 변환하면 0111 1111 1111 1111 1111 1111 1111 1111 이며 이것은 Java은 int 32비트 정수형이다. 따라서 int 형의 hash값을 해당 비트와 비트 연산을 하면 만약 hash 값의 음수여도 비트 연산하는 비트의 부호 비트가 0이고, 이것과 and 연산을 하므로 1은 0으로 바뀌게 된다.

이것은 배열의 인덱스를 참조할 때 음수의 값은 허용되지 않기 때문이다.

profile
좋은 영향력과 교류를 위하여

0개의 댓글