关于map的遍历问题

刚才想打印map里的值的时候,首先想到是就是的迭代器,但看了一下map,没有迭代器的相关方法,才知道map遍历不用迭代器

Set<Map.Entry<K, V>> entrySet();

Map里有这个方法,返回Map所有的映射,存进Set中

所以根据这个我们就可以知道如何遍历 Map了

for(Map.Entry<String,Object> entry :treemap.entrySet()) {
        	System.out.println("key: "+entry.getKey()+" value: "+entry.getValue());
        }

Map.Entry是Map的一个内部接口

interface Entry<K,V> {
        //返回Key
        K getKey();

        //返回对应的value
        V getValue();

        //用指定的值替换对应的值
        V setValue(V value);

        ......
    }
public Set<Map.Entry<K,V>> entrySet() {
        EntrySet es = entrySet;
        return (es != null) ? es : (entrySet = new EntrySet());
    }

private transient EntrySet entrySet;

猜你喜欢

转载自blog.csdn.net/qq_35815781/article/details/85070062