JAVA遍歷Map所有元素

2021-05-22 11:59:42 字數 848 閱讀 2965

//

jdk1.5   

map map

=new

hashmap();     

for(object obj : map.keyset())

//jdk1.4   

map map

=new

hashmap()    ;     

iterator iter

=map.entryset().iterator();     

while

(iter.hasnext())  

第一種:

map map

= new hashmap();

iterator iter = map

.entryset().iterator();

while (iter.hasnext())

效率高,以後一定要使用此種方式!

第二種:

map map

= new hashmap();

iterator iter = map

.keyset().iterator();

while (iter.hasnext())

效率低,以後盡量少使用!

例:hashmap的遍歷有兩種常用的方法,那就是使用keyset及entryset來進行遍歷,但兩者的遍歷速度是有差別的,下面請看例項:

對於keyset其實是遍歷了2次,一次是轉為iterator,一次就從hashmap中取出key所對於的value。而entryset只是遍歷了第一次,他把key和value都放到了entry中,所以就快了。

注:hashtable的遍歷方法和以上的差不多!

Java如何遍歷Map的所有的元素

jdk1.4中 map map new hashmap iterator it map.entryset iterator while it.hasnext jdk1.5中,應用新特性for each迴圈 map m new hashmap for object o map.keyset 返回的 s...

Java如何遍歷Map的所有的元素

jdk1.4中 map map new hashmap iterator it map.entryset iterator while it.hasnext jdk1.5中,應用新特性for each迴圈 map m new hashmap for object o map.keyset 返回的 s...

Java如何遍歷Map的所有的元素

jdk1.4中 map map new hashmap iterator it map.entryset iterator while it.hasnext jdk1.5中,應用新特性for each迴圈 map m new hashmap for object o map.keyset 返回的 s...