자료구조

[자료구조] Hash Table (해시 테이블)

Joo.v7 2024. 9. 7. 18:34

Hash Table 

  •  Hash를 이용해 Key와 Value 쌍으로 이루어진 데이터를 저장하는 전통적 자료구조.
  • Equality Selection 할 때, 가장 효율적인 자료구조.
  • Java에서는 주로 Hash Map을 사용할 것.

 

코드

/* HashTable.java */
import java.util.Iterator;

@SuppressWarnings("unchecked")
public class HashTable<K, V> implements Iterable<HashTable.Entry<K, V>>{
    private Entry<K, V>[] table;
    private int size;

    public static class Entry<K, V> {
        final K key; // '키'는 유일해야 하기 때문에
        V value;

        public Entry(K key, V value) {
            this.key = key;
            this.value = value;
        }
    }

    public HashTable() {
        this.table = new Entry[10];
    }

    public int hashFunction(K key) {
        return Math.abs(key.hashCode()) % table.length;
    }

    public void put(K key, V value) {
        int index = this.hashFunction(key);
        Entry<K, V> newEntry = new Entry<>(key, value);

        if (this.table[index] == null) {
            this.table[index] = newEntry;
        }
        else {
            this.table[index].value = value;
        }
        size++;
    }
    public V get(K key) {
        int index = this.hashFunction(key);
        return this.table[index].value;
    }

    public Iterator<Entry<K, V>> iterator() {
        return java.util.Arrays.stream(this.table).iterator();
    }
}

class Test {
    public static void main(String[] args) {
        HashTable<String, String> hashtable = new HashTable<>();
        hashtable.put("A", "Hello");
        hashtable.put("B", "World");
        hashtable.put("C", "!!!!!");

        System.out.println(hashtable.get("A"));
        System.out.println(hashtable.get("B"));
        System.out.println(hashtable.get("C"));
    }
}

 

실행 결과

Hello
World
!!!!!

 

 

2024.09.02 - [Java] - [Java] 14. Collections Framework

 

[Java] 14. Collections Framework

Chapter 1: Collection FrameworkCollection 개요Java Collections FrameworkCollection 클래스의 저장 구조Java Collections Framework 구성Collection 인터페이스Collection 인터페이스의 주요 메소드 Chapter 2: Iterator, Comparable, Compa

lightningtech.tistory.com

 


 

 

출처: https://github.com/gikpreet/class-programming_with_java/tree/master

 

GitHub - gikpreet/class-programming_with_java

Contribute to gikpreet/class-programming_with_java development by creating an account on GitHub.

github.com