第一种:
class="java" name="code">Map map = new HashMap();
Iterator iter = map.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry entry = (Map.Entry) iter.next();
Object key = entry.getKey();
Object val = entry.getValue();
}
效率高,以后一定要使用此种方式!
第二种:
Map map = new HashMap();
Iterator iter = map.keySet().iterator();
while (iter.hasNext()) {
Object key = iter.next();
Object val = map.get(key);
}
效率低,以后尽量少使用!
import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;
public class HashMapTest {
public static void main(String[] args) {
keySet();
entrySet();
}
public static void keySet() {
HashMap<Integer,String> hashmap = new HashMap<Integer,String>();
for (int i = 0; i < 1000; i++) {
hashmap.put(i, "thanks");
}
long bs = Calendar.getInstance().getTimeInMillis();
Iterator iterator = hashmap.keySet().iterator();
while (iterator.hasNext()) {
System.out.print(hashmap.get(iterator.next()));
}
System.out.println();
System.err.println(Calendar.getInstance().getTimeInMillis() - bs);
}
public static void entrySet() {
HashMap<Integer,String> hashmap = new HashMap<Integer,String>();
for (int i = 0; i < 1000; i++) {
hashmap.put(i, "thanks");
}
long bs = Calendar.getInstance().getTimeInMillis();
Iterator it = hashmap.entrySet().iterator();
while (it.hasNext()) {
Entry entry = (Entry) it.next();
// entry.getKey() 返回与此项对应的键
// entry.getValue() 返回与此项对应的值
System.out.print(entry.getValue());
}
System.out.println();
System.err.println(Calendar.getInstance().getTimeInMillis() - bs);
}
}