怎么遍历得到map的所有数据

可以通过 put 和 get 的方式, 往map中put元素,或者 get 获取元素。

  如何得到map中的所有元素呢?

 

获取HashMap中的所有key。

public class Main {
    public static void main(String[] args){
        HashMap<Integer,String> map = new HashMap<>();
        map.put(1,"a");
        map.put(2,"b");
        map.put(3,"c");
        map.put(4,"d");
        Set<Integer> integers = map.keySet();    // 
        System.out.println(integers.size());
    }
}

 

keySet( ) 方法。

public Set<K> keySet() {
        Set<K> ks = keySet;
        if (ks == null) {
            ks = new KeySet();    // 如何做到 创建了 KeySet对象,就含有了所有的key
            keySet = ks;
        }
        return ks;
    }

map中的key 是在什么时候加入到 keySet中的呢??

 

 

 

  

posted @ 2020-09-14 15:33  你眼里的星辰  阅读(639)  评论(0)    收藏  举报