在Java中,可以使用以下幾種方法遍歷Hashtable:
Enumeration
遍歷Hashtable的鍵和值:import java.util.Hashtable;
import java.util.Enumeration;
public class Main {
public static void main(String[] args) {
Hashtable<String, Integer> hashtable = new Hashtable<>();
hashtable.put("one", 1);
hashtable.put("two", 2);
hashtable.put("three", 3);
// 遍歷鍵
Enumeration<String> keys = hashtable.keys();
while (keys.hasMoreElements()) {
String key = keys.nextElement();
System.out.println("Key: " + key);
}
// 遍歷值
Enumeration<Integer> values = hashtable.elements();
while (values.hasMoreElements()) {
Integer value = values.nextElement();
System.out.println("Value: " + value);
}
}
}
Iterator
遍歷Hashtable的鍵和值(需要將Hashtable轉(zhuǎn)換為Map):import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
public class Main {
public static void main(String[] args) {
Hashtable<String, Integer> hashtable = new Hashtable<>();
hashtable.put("one", 1);
hashtable.put("two", 2);
hashtable.put("three", 3);
// 將Hashtable轉(zhuǎn)換為Map
Map<String, Integer> map = hashtable;
// 遍歷鍵
Iterator<String> keys = map.keySet().iterator();
while (keys.hasNext()) {
String key = keys.next();
System.out.println("Key: " + key);
}
// 遍歷值
Iterator<Integer> values = map.values().iterator();
while (values.hasNext()) {
Integer value = values.next();
System.out.println("Value: " + value);
}
}
}
forEach
方法遍歷Hashtable的鍵值對(duì)(需要將Hashtable轉(zhuǎn)換為Map):import java.util.Hashtable;
import java.util.Map;
public class Main {
public static void main(String[] args) {
Hashtable<String, Integer> hashtable = new Hashtable<>();
hashtable.put("one", 1);
hashtable.put("two", 2);
hashtable.put("three", 3);
// 將Hashtable轉(zhuǎn)換為Map
Map<String, Integer> map = hashtable;
// 遍歷鍵值對(duì)
map.forEach((key, value) -> {
System.out.println("Key: " + key + ", Value: " + value);
});
}
}
這些方法都可以用來(lái)遍歷Hashtable。根據(jù)你的需求和Java版本,可以選擇合適的方法進(jìn)行遍歷。