当我在早先将其添加到外部地图后清理内部地图时,我感到震惊。有没有办法重置内部地图,但不能从外部地图中删除对象?
主要课程:
public static void main(String args[]) {
Person per1 = new Person("1", "aaa",56, true);
Person per2 = new Person("20", "bbb",34, false);
Map<Integer, Map<Integer, Person>> outer = new HashMap<Integer, Map<Integer, Person>>();
Map<Integer, Person> inner = new HashMap<Integer, Person>();
inner.put(100, per1);
inner.put(200, per2);
outer.put(1000, inner);
// inner: size = 2 , outer: size = 1 (key = 1000, value size = 2)
inner.clear();
// inner: size = 0 , outer: size = 1 (key = 1000, value size = 0)
// why outer value size = 0 ?
}
人:
public class Person {
private String id;
private String name;
private int age;
private boolean isSome;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public boolean isSome() {
return isSome;
}
public void setSome(boolean isPaid) {
this.isSome = isPaid;
}
public Person(){}
public Person(String id, String name, int age, boolean isSome){
this.id = id;
this.name = name;
this.age = age;
this.isSome = isSome;
}
}
答案 0 :(得分:3)
outer.put(1000, inner);
将inner
变量中包含的引用作为外部Map中的值。它不会创建inner
引用的实例的副本,因此如果您稍后清除inner
地图,则还会清除存储在外部地图中的值。
如果希望外部Map的值是原始内部Map的副本,则可以创建新实例:
outer.put(1000, new HashMap<Integer, Person>(inner));
请注意,在这种情况下,新内部Map中的Person
个实例与原始Person
Map的原始inner
实例的实例相同,因此如果您改变其中一个它们,存储在Map中的实例也会发生变异。