Open 2d3k opened 1 year ago
동기화(synchronization) 처리 Hashtable은 멀티스레드 환경에서 안전하게 사용할 수 있도록 모든 메소드가 synchronized로 구현되어 있습니다. 따라서 멀티스레드 환경에서 안전하게 사용할 수 있습니다. 하지만 이로 인해 성능이 저하될 수 있습니다. HashMap은 동기화 처리가 되어 있지 않습니다. 멀티스레드 환경에서 사용할 경우 동기화 처리를 해주어야 합니다. 그러나 싱글스레드 환경에서는 동기화 처리를 하지 않기 때문에 더 빠르게 동작할 수 있습니다.
Null 값 허용 여부 Hashtable은 Key와 Value 모두 null 값을 허용합니다. 이는 종종 문제를 발생시키기 때문에 null 값을 허용하지 않는 것이 좋습니다. HashMap은 Key와 Value 중에 하나라도 null 값을 가질 수 있습니다. 하지만 보통은 Key값으로 null 값을 사용하지 않는 것이 좋습니다.
Iterator 지원 Hashtable은 Iterator를 지원하지 않습니다. Enumeration을 사용하여 요소를 순회할 수 있습니다. HashMap은 Iterator를 지원합니다. Iterator는 Enumeration보다 더 안전하고 빠릅니다.
성능 Hashtable과 HashMap의 성능 차이는 크지 않습니다. 하지만 동기화 처리가 되어 있기 때문에 Hashtable이 조금 느릴 수 있습니다. 그러나 실제로는 데이터의 크기와 요청 횟수 등에 따라 다를 수 있습니다. 따라서, 요약하면, Hashtable은 동기화 처리가 되어 있어 멀티스레드 환경에서 안전하게 사용할 수 있으나, 성능이 느릴 수 있고 null 값을 허용합니다. HashMap은 동기화 처리가 되어 있지 않아 멀티스레드 환경에서는 동기화 처리를 해주어야 하지만, 더 빠른 성능을 가지며, Key나 Value 중에 하나라도 null 값을 가질 수 있습니다. 또한, Iterator를 지원합니다.
import java.util.HashMap;
import java.util.Hashtable;
public class Example {
public static void main(String[] args) {
// Creating a HashMap
HashMap<String, Integer> hashMap = new HashMap<String, Integer>();
// Adding elements to the HashMap
hashMap.put("Alice", 25);
hashMap.put("Bob", 30);
hashMap.put("Charlie", 35);
// Printing the HashMap
System.out.println("HashMap: " + hashMap);
// Accessing elements in the HashMap
int age = hashMap.get("Alice");
System.out.println("Alice's age: " + age);
// Creating a HashTable
Hashtable<String, String> hashTable = new Hashtable<String, String>();
// Adding elements to the HashTable
hashTable.put("apple", "red");
hashTable.put("banana", "yellow");
hashTable.put("orange", "orange");
// Printing the HashTable
System.out.println("HashTable: " + hashTable);
// Accessing elements in the HashTable
String color = hashTable.get("banana");
System.out.println("Banana's color: " + color);
}
}
1. Hash란?
2. HashMap, HashTable의 차이는무엇인가요?
3. 자바의 구현 방법을 기술하시오.