第一种:
Iterator iter
= map.
entrySet().
iterator();
while (iter.hasNext()) {
Object val
= entry.
getValue();
}
效率高,以后一定要使用此种方式!
第二种:
Iterator iter
= map.
keySet().
iterator();
while (iter.hasNext()) {
}
效率低,以后尽量少使用!
HashMap的遍历有两种常用的方法,那就是使用keyset及entryset来进行遍历,但两者的遍历速度是有差别的,下面请看实例:
public class HashMapTest {
public static void main
(String[] args
) ...
{
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()));
}
listHashMap();
}
public static void listHashMap() ...{
for (int i = 0; i < 1000; i ) ...{
hashmap.put("" i, "thanks");
}
long bs
= Calendar.
getInstance().
getTimeInMillis();
java.
util.
Iterator it
= hashmap.
entrySet().
iterator();
while (it.hasNext()) ...{
// entry.getKey() 返回与此项对应的键
// entry.getValue() 返回与此项对应的值
System.
out.
print(entry.
getValue());
}
}
}
对于keySet其实是遍历了2次,一次是转为iterator,一次就从hashmap中取出key所对于的value。而entryset只是遍历了第一次,他把key和value都放到了entry中,所以就快了。
<font color="#e78608">------解决思路----------------------</font>
<fieldset>
<legend>探讨</legend>
关键是我这值 不确定
所以我想
map.get(1);
map.get(2);
这样最好........
</fieldset> //源代码片段来自云代码http://yuncode.net