map.keySet()修改会影响原map

map的keySet()方法返回的集合,对集合进行添加或者删除会影响到原来的集合map

    public static void main(String args[]) {

        Map map = new HashMap();
        map.put("1", "a");
        map.put("2", "b");
        Set<String> custNumSet = map.keySet();
        List list = new ArrayList<>();
        list.add("1");
        custNumSet.removeAll(list);
        custNumSet.add("2");
        map.forEach((k, v) -> {
            System.out.println(map.get(k));
        });
    }

进行add操作会报错

 进行removeAll操作会改变原有map集合

所以 在使用时需要注意

猜你喜欢

转载自blog.csdn.net/LiZhen314/article/details/127315607