Post
[자료구조]맵, 해시테이블
맵(Map)
목록으로 관리 ( 배열, 리스트 ) => 인덱스로 조회
맵 => 키로 조회 (Key , Value 쌍)
키는 중복될 수 없음
import java.util.HashMap; import java.util.Map;
public class test8 { public static void main(String[] args){ Map<String, Object> map = new HashMap<>();
map.put(“Name”,”Kms”); map.put(“Age”,”Secret”); map.put(“Nation”,”Korea”); System.out.println(map); System.out.println(“Age:”+map.get(“Age”)); System.out.println(“bf : “+map.containsKey(“Nation”)); map.remove(“Nation”); System.out.println(“af : “+map.containsKey(“Nation”));
for (String key :map.keySet()){ System.out.println(“Key:” + key + “, Value:”+ map.get(key)); } } }
맵 사용 : 데이터 저장 및 검색, 캐싱, JSON, XML 등 .. 맨날 쓰는거에 다 쓰입니다.
맵에다 리스트 저장 가능합니다. (Ex. map 키에다가 List 넣기)
해시 테이블(Hash Table)
키,쌍 저장하는 자료구조
해시 함수를 사용해 키를 해시값으로 변환해서 해당 해시 값을 인덱스로 사용해 값을 저장하고 검색
충돌 시, 체이닝은 임시로 연결해서 첫번째는 apple이지만 두번째는 grape임을 표시
개방주소법은 임시로 다음 빈버킷에 새로운 값쌍을 넣어줌. 원래는 1번이지만 충돌되서 임시로 여기에 들어가 있다는 정보가 담김
import java.util.Hashtable;
public class HashTableExample { public static void main(String[] args) { // 해시 테이블 생성 Hashtable<Integer, String> hashTable = new Hashtable<>();
// 데이터 추가 System.out.println(“데이터 추가:”); hashTable.put(1, “Apple”); hashTable.put(2, “Banana”); hashTable.put(3, “Cherry”); hashTable.put(4, “Date”);
// 내용 출력 System.out.println(“현재 해시 테이블: “ + hashTable);
// 중복 키 처리 (기존 값 덮어쓰기) System.out.println(“\n중복된 키에 값 추가:”); hashTable.put(2, “Blueberry”); // 키 2에 새로운 값 추가 System.out.println(“현재 해시 테이블: “ + hashTable);
// 값 삭제 System.out.println(“\n값 삭제:”); hashTable.remove(3); // 키 3 삭제 System.out.println(“현재 해시 테이블: “ + hashTable);
// 해시 테이블에서 값 찾기 System.out.println(“\n값 찾기:”); String value = hashTable.get(1); // 키 1의 값 찾기 System.out.println(“키 1의 값: “ + value);
// 키가 존재하는지 확인 System.out.println(“\n키 존재 여부 확인:”); boolean containsKey = hashTable.containsKey(3); // 키 3이 존재하는지 확인 System.out.println(“키 3이 존재하는지: “ + containsKey);
// 값이 존재하는지 확인 boolean containsValue = hashTable.containsValue(“Banana”); // 값 ‘Banana’가 존재하는지 확인 System.out.println(“값 ‘Banana’가 존재하는지: “ + containsValue);
// 해시 테이블 크기 System.out.println(“\n해시 테이블의 크기: “ + hashTable.size()); } }
🔹 1. Map과 HashTable의 기본 개념
📌 Map이란?
- Key-Value(키-값) 쌍을 저장하는 자료구조를 의미하는 “인터페이스”(추상적인 개념).
- java.util.Map 인터페이스를 구현한 여러 클래스가 존재함.
- → 예: HashMap, TreeMap, LinkedHashMap, HashTable 등
- 순수한 개념적인 인터페이스이므로 직접 객체를 생성할 수 없음.
📌 HashTable이란?
- Map 인터페이스의 구현체 중 하나.
- 해시 함수를 사용해 데이터를 저장하는 자료구조.
- 멀티스레드 환경에서도 안전(동기화 지원)하지만, 성능이 떨어짐.
- HashTable 클래스는 예전부터 존재했던 클래스로, 요즘은 잘 사용하지 않음.
- → 대신 ConcurrentHashMap을 사용함.
🔹 2. 주요한 차이점 비교
| 차이점 | Map(인터페이스) | HashTable(구현체) |
|---|---|---|
| 정의 | 키-값 쌍을 저장하는 개념적인 인터페이스 | 해시 기반으로 키-값을 저장하는 클래식한 구현체 |
| 구현 클래스 | HashMap, TreeMap, LinkedHashMap, HashTable 등 | HashTable (옛날 방식) |
| 멀티스레드 지원 | ❌ (HashMap은 동기화 X) | ✅ (synchronized 지원) |
| null 허용 여부 | HashMap: ✅ (null 키, null 값 가능) | ❌ (null 키, null 값 불가능) |
| 성능 | HashMap이 더 빠름 | synchronized로 인해 느림 |
| 사용 추천 여부 | HashMap 또는 ConcurrentHashMap 추천 | 요즘은 거의 사용하지 않음 |
🔹 3. HashMap vs HashTable
📌 HashMap
import java.util.*;
public class Main { public static void main(String[] args) { Map<String, Integer> map = new HashMap<>(); map.put(“apple”, 10); map.put(“banana”, 5); map.put(null, 100); // ✅ null 키 허용 map.put(“grape”, null); // ✅ null 값 허용
System.out.println(map); } }
✅ null 키와 null 값 허용, 빠름. (싱글 스레드 환경에서 유용함)
📌 HashTable
import java.util.*;
public class Main { public static void main(String[] args) { Map<String, Integer> table = new Hashtable<>(); table.put(“apple”, 10); table.put(“banana”, 5); // table.put(null, 100); // ❌ NullPointerException 발생! // table.put(“grape”, null); // ❌ NullPointerException 발생!
System.out.println(table); } }
🚫 null 키와 null 값 허용 안 됨. 멀티스레드 환경에서 안전하지만 느림.
🔹 4. 결론
- Map은 인터페이스이며, HashMap, TreeMap, LinkedHashMap, HashTable 등의 구현체가 있음.
- HashMap은 null 허용, 성능이 뛰어나므로 일반적으로 더 많이 사용됨.
- HashTable은 동기화 지원하지만 느려서 잘 사용하지 않음.
- → 대신 ConcurrentHashMap을 사용하면 동기화와 성능을 모두 잡을 수 있음.
💡 즉, 대부분의 경우 HashMap을 사용하고, 멀티스레드 환경에서는 ConcurrentHashMap을 사용하면 됨! 🚀
댓글