今天发现在map<K,V>集合中的keySet()方法获取到的Set集合后,我对这个Set做remove操作竟然会影响到map<K,V>集合
代码如下
package com.Sykking.Test;
import com.Sykking.Test.Util.check;
import java.util.*;
public class MyTest {
public static void main(String[] args) {
HashMap<Integer,String> hashMap = new HashMap<>();
hashMap.put(1,"1");
hashMap.put(2,"2");
hashMap.put(3,"3");
Set<Integer> keySet = hashMap.keySet();//获取key集合
System.out.print("第一次遍历结果");
for (Integer i:keySet) {
System.out.print(i+"\t");//遍历keySet
}
System.out.println();
System.out.print("第二次遍历结果");
keySet.remove(2);//为什么执行到这步竟然把map的value也给删除了? 我只是操作了遍历出来的key集合阿
//重新遍历key发现map里的<2,"2">已经被删除了
Set<Integer> keySet2 = hashMap.keySet();
for (Integer i:keySet2) {
System.out.print(i+"\t");
}
}
}
后来查了API发现他们是绑定的,互相操作会有影响的
最后我想在不影响map<K,V>集合的情况下操作Set集合 所以用的笨办法 使用了List集合存储Set的值,然后对List做操作了