ν΄μ맡(HashMap)
ν΄μ맡μ ν€(Key)μ κ°(Value)μΌλ‘ ꡬμ±λ Entry κ°μ²΄λ₯Ό μ μ₯νλ ꡬ쑰λ‘μ¨, ν΄μ ν¨μ(Hash Function)λ₯Ό μ¬μ©νμ¬ ν€λ₯Ό ν΄μκ°μΌλ‘ 맀ννκ³ , μ΄ ν΄μκ°μΌλ‘ κ°μ μ μ₯νκ±°λ κ²μνλ μλ£κ΅¬μ‘°μ
λλ€.
ν΅μ¬ μμ
μμ | μ€λͺ
|
ν€(Key) | κ³ μ ν μλ³μλ‘ μ¬μ©λλ©°, μ€λ³΅λ μ μμ |
κ°(Value) | ν€μ 맀νλλ λ°μ΄ν° |
ν΄μ ν¨μ | ν€λ₯Ό ν΄μκ°μΌλ‘ λ³ννλ ν¨μ |
λ²ν·(Bucket) | μ€μ λ°μ΄ν°κ° μ μ₯λλ κ³΅κ° |
λ‘λ ν©ν° | ν΄μ맡μ ν¬κΈ°λ₯Ό κ²°μ νλ μμ |
μ§μ ꡬν μμ μ½λ
public class SimpleHashMap<K, V> {
private static class Entry<K, V> {
K key;
V value;
Entry<K, V> next;
Entry(K key, V value) {
this.key = key;
this.value = value;
}
}
private Entry<K, V>[] buckets;
private static final int INITIAL_CAPACITY = 16;
@SuppressWarnings("unchecked")
public SimpleHashMap() {
buckets = new Entry[INITIAL_CAPACITY];
}
public void put(K key, V value) {
int index = Math.abs(key.hashCode() % INITIAL_CAPACITY);
if (buckets[index] == null) {
buckets[index] = new Entry<>(key, value);
} else {
Entry<K, V> current = buckets[index];
while (current != null) {
if (current.key.equals(key)) {
current.value = value;
return;
}
current = current.next;
}
Entry<K, V> newEntry = new Entry<>(key, value);
newEntry.next = buckets[index];
buckets[index] = newEntry;
}
}
public V get(K key) {
int index = Math.abs(key.hashCode() % INITIAL_CAPACITY);
Entry<K, V> current = buckets[index];
while (current != null) {
if (current.key.equals(key)) {
return current.value;
}
current = current.next;
}
return null;
}
}
Java
볡μ¬
Java Collections Framework μ¬μ© μμ
import java.util.HashMap;
import java.util.Map;
public class HashMapExample {
public static void main(String[] args) {
// HashMap μμ±
HashMap<String, Integer> scores = new HashMap<>();
// λ°μ΄ν° μΆκ°
scores.put("Kim", 95);
scores.put("Lee", 85);
scores.put("Park", 90);
// λ°μ΄ν° μ‘°ν
System.out.println("Kim's score: " + scores.get("Kim"));
// λ°μ΄ν° μν
for (Map.Entry<String, Integer> entry : scores.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
// ν€ μ‘΄μ¬ μ¬λΆ νμΈ
System.out.println("Contains Kim? " + scores.containsKey("Kim"));
// λ°μ΄ν° μμ
scores.remove("Lee");
// ν¬κΈ° νμΈ
System.out.println("Size: " + scores.size());
}
}
Java
볡μ¬