在Java中,Hashtable
是一個(gè)用于存儲鍵值對的數(shù)據(jù)結(jié)構(gòu)
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);
下面是一個(gè)完整的示例代碼:
import java.util.Hashtable;
public class HashtableExample {
public static void main(String[] args) {
// 創(chuàng)建一個(gè)Hashtable實(shí)例
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中是否包含某個(gè)鍵
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的大小(元素個(gè)數(shù))
int size = hashtable.size();
System.out.println("Size of Hashtable: " + size);
}
}
運(yùn)行這段代碼,你將看到以下輸出:
Value of key1: value1
Hashtable contains key1: true
Key: key3, Value: value3
Key: key2, Value: value2
Size of Hashtable: 2