在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