在Java中,Hashtable
是一個用于存儲鍵值對的數據結構
import java.util.Hashtable;
Hashtable<String, String> hashtable = new Hashtable<>();
hashtable.put("key1", "value1");
hashtable.put("key2", "value2");
hashtable.put("key3", "value3");
String value = hashtable.get("key1");
System.out.println("Value of key1: " + value);
boolean containsKey = hashtable.containsKey("key1");
System.out.println("Hashtable contains key1: " + containsKey);
hashtable.remove("key1");
for (String key : hashtable.keySet()) {
String value = hashtable.get(key);
System.out.println("Key: " + key + ", Value: " + value);
}
int size = hashtable.size();
System.out.println("Size of Hashtable: " + size);
下面是一個完整的示例代碼:
import java.util.Hashtable;
public class HashtableExample {
public static void main(String[] args) {
// 創建一個Hashtable實例
Hashtable<String, String> hashtable = new Hashtable<>();
// 向Hashtable中添加元素
hashtable.put("key1", "value1");
hashtable.put("key2", "value2");
hashtable.put("key3", "value3");
// 從Hashtable中獲取元素
String value = hashtable.get("key1");
System.out.println("Value of key1: " + value);
// 檢查Hashtable中是否包含某個鍵
boolean containsKey = hashtable.containsKey("key1");
System.out.println("Hashtable contains key1: " + containsKey);
// 刪除Hashtable中的元素
hashtable.remove("key1");
// 遍歷Hashtable中的所有鍵值對
for (String key : hashtable.keySet()) {
String val = hashtable.get(key);
System.out.println("Key: " + key + ", Value: " + val);
}
// 獲取Hashtable的大小(元素個數)
int size = hashtable.size();
System.out.println("Size of Hashtable: " + size);
}
}
運行這段代碼,你將看到以下輸出:
Value of key1: value1
Hashtable contains key1: true
Key: key3, Value: value3
Key: key2, Value: value2
Size of Hashtable: 2