HashMap<String, String> hm = new HashMap<>(8);
hm.put(“重地”,“1”);
hm.put(“通话”,“2”);
hm.values().forEach(str-> System.out.println(str));
for (String value : hm.values()) {
// hm.put(“qfc”,“123”);//java.util.ConcurrentModificationException
// hm.remove(“重地”);//java.util.ConcurrentModificationException
}
}
private static void keySetTest() {
HashMap<String, String> hm = new HashMap<>(8);
hm.put(“重地”,“1”);
hm.put(“通话”,“2”);
hm.keySet().forEach(str-> System.out.println(str));
for (String s : hm.keySet()) {
// hm.put(“qfc”,“1”);//java.util.ConcurrentModificationException
// hm.remove(“通话”);//java.util.ConcurrentModificationException
}
}
private static void cloneTest() {
HashMap<Person, String> hm = new HashMap<>(8);
Person p1 = new Person(“qfc”,18);
Person p2 = new Person(“zyx”,19);
hm.put(p1,“1”);
hm.put(p2,“2”);
/**
-
clone方法
-
首先HashMap clone = super.clone();获得克隆对象
-
然后clone对象重置HashMap的属性,table,threshold,size,modcount,entrySet,keySey,values
-
然后重新将super的key-value重新put进clone中
-
由于clone和super中的对应key和value都是指向同一个对象,所以还是属于浅克隆
*/
HashMap<Person, String> clone = (HashMap) hm.clone();
clone.put(p1,“3”);
System.out.println(hm.get(p1));//1
System.out.println(clone.get(p1));//3
Person next = clone.keySet().iterator().next();
next.setAge(100);
Person next1 = hm.keySet().iterator().next();
System.out.println(next1.getAge());//100
for (Map.Entry<Person, String> personStringEntry : hm.entrySet()) {
System.out.println(personStringEntry.getKey());
}
// Person{name=‘qf