作者:胡萝卜咯198408 | 来源:互联网 | 2022-12-23 15:53
HashMap和Hashtable的遍历
HashMap |
Hashtable |
keySet() |
keySet() |
entrySet() |
entrySet() |
value() |
elements() |
iterator |
iterator |
此外,Hashtable还可以使用keys() 和Enumeration进行遍历,闲言少叙,直接上代码
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
public class Test {
public static void main(String[] args) {
int[] arr = {0,1,2,3,4,5,6,7,8,9};
HashMap map = new HashMap<>();
Hashtable table = new Hashtable<>();
for(int i = 0; i <10; i++) {
map.put(arr[i], arr[i]);
table.put(arr[i], arr[i]);
}
System.out.println("-----------------HashMap遍历------------------------");
System.out.println("1.使用keySet()");
for(Integer key : map.keySet()) {
System.out.println(key + " : " + map.get(key));
}
System.out.println("2.使用entrySet()");
for(Map.Entry entry : map.entrySet()) {
System.out.println(entry.getKey() + " : " + entry.getValue());
}
System.out.println("3.使用value(),但不能得到key");
for(Integer i : map.values()) {
System.out.println(i);
}
System.out.println("4.使用Iterator");
Iterator> it = map.entrySet().iterator();
while(it.hasNext()) {
Map.Entry entry = it.next();
System.out.println(entry.getKey() + " : " + entry.getValue());
}
System.out.println("-----------------Hashtable遍历------------------------");
System.out.println("1.使用keySet()");
for(Integer key : table.keySet()) {
System.out.println(key + " : " + table.get(key));
}
System.out.println("2.使用keys()");
Enumeration en1 = table.keys();
while(en1.hasMoreElements()) {
int key = en1.nextElement();
System.out.println(key + " : " + table.get(key));
}
System.out.println("3.使用entrySet()");
Iterator> it1 = table.entrySet().iterator();
while(it1.hasNext()) {
Map.Entry entry = it1.next();
System.out.println(entry.getKey() + " : " + entry.getValue());
}
System.out.println("4.使用elements(),相当于遍历value");
Enumeration en2 = table.elements();
while(en2.hasMoreElements()) {
System.out.println(en2.nextElement());
}
}
}
注:HashMap和Hashtable的存储和遍历都是无序的