Java中Hashtable哈希表的遍历方式
在Java中,Hashtable是一个已经过时的集合类,建议使用HashMap替代。但是,如果你需要遍历Hashtable,可以使用以下几种方法:
- 使用keySet()和Iterator遍历:
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
public class Main {
public static void main(String[] args) {
Hashtable hashtable = new Hashtable<>();
hashtable.put("one", 1);
hashtable.put("two", 2);
hashtable.put("three", 3);
Iterator> iterator = hashtable.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry entry = iterator.next();
System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
}
}
}
- 使用keySet()和for-each循环遍历:
import java.util.Hashtable;
import java.util.Map;
public class Main {
public static void main(String[] args) {
Hashtable hashtable = new Hashtable<>();
hashtable.put("one", 1);
hashtable.put("two", 2);
hashtable.put("three", 3);
for (String key : hashtable.keySet()) {
System.out.println("Key: " + key + ", Value: " + hashtable.get(key));
}
}
}
- 使用entrySet()和for-each循环遍历:
import java.util.Hashtable;
import java.util.Map;
public class Main {
public static void main(String[] args) {
Hashtable hashtable = new Hashtable<>();
hashtable.put("one", 1);
hashtable.put("two", 2);
hashtable.put("three", 3);
for (Map.Entry entry : hashtable.entrySet()) {
System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
}
}
}
- 使用values()和for-each循环遍历:
import java.util.Hashtable;
public class Main {
public static void main(String[] args) {
Hashtable hashtable = new Hashtable<>();
hashtable.put("one", 1);
hashtable.put("two", 2);
hashtable.put("three", 3);
for (Integer value : hashtable.values()) {
System.out.println("Value: " + value);
}
}
}
以上四种方法都可以实现Hashtable的遍历。但是,建议使用HashMap替代Hashtable,因为HashMap提供了更好的性能和更多的功能。