
- HashMap과 구조가 비슷하지만 용도가 다르다.
- 키와 값을 1:1형태로 가져간다.
- 동기화가 이루어진다.
- null 입력이 불가능하다.
선언
import java.util.Hashtable;
public class HashTableDemo {
public static void main(String[] arg) {
Hashtable ht = new Hashtable(); // 타입 설정x Object 설정
Hashtable<Integer, Integer> i = new Hashtable<Integer, Integer>(); // Integer, Integer 타입 선언
Hashtable<Integer, Integer> i2 = new Hashtable<>(); // new는 타입 생략 가능
Hashtable<Integer, Integer> i3 = new Hashtable<Integer, Integer>(i); // i의 Hashtable을 i3으로 값 이전
Hashtable<Integer, Integer> i4 = new Hashtable<Integer, Integer>(10); // 초기 용량 지정
Hashtable<Integer, Integer> i5 = new Hashtable<Integer, Integer>() {{ // 변수 선언 + 초기값 지정
put(1, 100); put(2, 200)
}}
Hashtable<String, String> str = new Hashtable<Integer, Integer>(); // String, String 타입 선언
Hashtable<Character, Character> str = new Hashtable<Character, Character>(); // Char, Char 타입 선언
}
}
값 추가 및 변경
import java.util.Hashtable;
public class Test {
public static void main(String[] arg) {
Hashtable<Integer, String> hashtable = new Hashtable<>();
hashtable.put(0, "첫 번째 값");
hashtable.put(1, "두 번째 값");
hashtable.put(2, "세 번째 값");
hashtable.put(3, "네 번째 값");
}
}

- 입력한 역순으로 키와 벨류가 나온다.
import java.util.Hashtable;
public class Test {
public static void main(String[] arg) {
Hashtable<Integer, String> hashtable = new Hashtable<>();
hashtable.put(0, "첫 번째 값");
hashtable.put(1, "두 번째 값");
hashtable.put(2, "세 번째 값");
hashtable.put(3, "네 번째 값");
System.out.println(hashtable.getOrDefault(0, ""));
hashtable.replace(0, "수정된 첫 번째 값");
System.out.println(hashtable.getOrDefault(0, ""));
}
}

값 삭제
import java.util.Hashtable;
public class HashTableDemo {
public static void main(String[] arg) {
Hashtable<String, String> ht = new Hashtable<>(); // Hashtable 선언
hashtable.put("1", "Hello1");
hashtable.put("2", "Hello2");
hashtable.put("3", "Hello3");
hashtable.put("4", "Hello4");
System.out.println(ht);
ht.remove("2");
System.out.println(ht);
ht.clear();
System.out.println(ht);
}
}

전체 값 확인
import java.util.Hashtable;
public class Test {
public static void main(String[] arg) {
Hashtable<Integer, String> hashtable = new Hashtable<>();
hashtable.put(0, "첫 번째 값");
hashtable.put(1, "두 번째 값");
hashtable.put(2, "세 번째 값");
hashtable.put(3, "네 번째 값");
System.out.println("전체 Key 확인 = " + hashtable.keySet());
System.out.println("전체 Value 확인 = " + hashtable.values());
}
}

값 존재 유무 확인
import java.util.Hashtable;
public class Test {
public static void main(String[] arg) {
Hashtable<Integer, String> hashtable = new Hashtable<>();
hashtable.put(0, "첫 번째 값");
hashtable.put(1, "두 번째 값");
hashtable.put(2, "세 번째 값");
hashtable.put(3, "네 번째 값");
System.out.println(hashtable.containsKey(2));
System.out.println(hashtable.containsValue("다섯번째 값"));
}
}
'자료구조' 카테고리의 다른 글
[자료구조] TreeMap (0) | 2023.11.10 |
---|---|
[자료구조] HashMap (0) | 2023.11.09 |
[자료구조] TreeSet (0) | 2023.11.07 |
[자료구조] Hash Set (0) | 2023.11.07 |
[자료구조] Vector (0) | 2023.11.06 |