show you the code:
public class T {
public static void main(String[] args) {
HashMap<String, Object> map = new HashMap<>();
map.put("c",20);
map.put("d",40);
Set<String> strings = map.keySet();
strings.add("d");
System.out.println(strings);
}
}
结果:
看看 Map.keySet() 方法上面的注释:
解释是:
keySet()返回此映射中所包含的键的 set 视图。该集合受映射的支持,所以映射的变化也反映在该集合中,反之亦然。该集合支持元素的移除,通过 Iterator.remove、Set.remove、removeAll、retainAll 和 clear 操作,从该映射中移除相应的映射关系。它不支持 add 或 addAll 操作。
code 01 :
public class T {
public static void main(String[] args) {
HashMap<String, Object> map = new HashMap<>();
map.put("c",20);
map.put("d",40);
Set<String> strings = map.keySet();
map.remove("c");
map.put("e", 50);
System.out.println(strings);
}
}
code 02 :
public class T {
public static void main(String[] args) {
HashMap<String, Object> map = new HashMap<>();
map.put("c",20);
map.put("d",40);
Set<String> strings = map.keySet();
strings.remove("c");
System.out.println(map);
}
}