Set<Map.Entry<K,V>> entrySet() 返回此映射中包含的映射关系的 set 视图。
Set<K> keySet() 返回此映射中包含的键的 set 视图。
举例说明
import java.util.*;
import java.util.Map.Entry;
public class Demo {
public static void main(String[] args) {
Map<Integer,String> map = new HashMap<Integer,String>();
map.put(1, "一");
map.put(2, "二");
map.put(3, "三");
map.put(4, "四");
map.put(5, "五");
/**
* 方法1keySet
*/
Set<Integer> keySet = map.keySet();
Iterator<Integer> iterator = keySet.iterator();
while (iterator.hasNext() ){
Integer key = iterator.next();
String value = map.get(key);
System.out.println("1.0"+key+"------"+value);
}
for (Iterator<Integer> it = keySet.iterator(); it.hasNext(); ) {
Integer key = it.next();
String value = map.get(key);
System.out.println("1.1"+key+"------"+value);
}
for (Integer key : keySet) {
String value = map.get(key);
System.out.println("1.2"+key+"------"+value);
}
/**
* 方法2entrySet
*/
Set<Entry<Integer, String>> entrySet = map.entrySet();
Iterator<Entry<Integer, String>> aiterator = entrySet.iterator();
while (aiterator.hasNext()) {
Entry<Integer, String> entry = aiterator.next();
Integer key = entry.getKey();
String value = entry.getValue();
System.out.println("2.0"+key+"------"+value);
}
for (Iterator<Entry<Integer, String>> it = entrySet.iterator(); it.hasNext(); ) {
Entry<Integer, String> entry = it.next();
Integer key = entry.getKey();
String value = entry.getValue();
System.out.println("2.1"+key+"------"+value);
}
for (Entry<Integer, String> entry : entrySet) {
Integer key = entry.getKey();
String value = entry.getValue();
System.out.println("2.2"+key+"------"+value);
}
}
}
keySet和entrySet的区别
keySet()的速度比entrySet()慢了很多,因为对于keySet其实是遍历了2次,一次是转为iterator,一次就从hashmap中取出key所对于的value。而entryset只是遍历了第一次,他把key和value都放到了entry中,所以就快了
for循环和while循环对比
1.for循环比for循环节约内存空间,因为迭代器在for循环中,循环结束,迭代器属于局部变量,循环结束就消失了,while循环中迭代器对象虽然也是局部变量但是要等方法运行完毕才能在内存中消失
2.当循环次数比较多时,while循环理论上要比for循环要高效,因为for循环比for多一条汇编语句
原文地址:http://blog.51cto.com/13579086/2070589
时间: 2024-11-02 23:21:34