Search

ν•΄μ‹œλ§΅

ν•΄μ‹œλ§΅(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
볡사