Java 初始化自身时,为什么要传递集合(或任何对象)的引用?请检查下面的代码
请检查下面代码的第5行。如果我的问题错了,也请纠正Java 初始化自身时,为什么要传递集合(或任何对象)的引用?请检查下面的代码,java,collections,immutable-collections,Java,Collections,Immutable Collections,请检查下面代码的第5行。如果我的问题错了,也请纠正 public class Location { private final Map<String, Integer> exits; public Location(Map<String, Integer> exits) { if(exits != null) { this.exits = new HashMap<String,
public class Location {
private final Map<String, Integer> exits;
public Location(Map<String, Integer> exits) {
if(exits != null) {
this.exits = new HashMap<String, Integer>(exits);
} else {
this.exits = new HashMap<String, Integer>();
}
}
}
公共类位置{
私人最终地图出口;
公共位置(地图出口){
如果(退出!=null){
this.exits=新的HashMap(exits);
}否则{
this.exits=new HashMap();
}
}
}
这个想法是封装地图,只允许通过位置
类接口中指定的路径访问数据
Location
对象的创建者和Location
类(或它可以实现的某些接口)的用户通常是系统中的两个不同组件。通过执行您显示为代码片段的操作,创建者将数据(地图)封装在类型为Location
的对象中,这样用户只能使用它执行许多操作(例如Location.calculateInstance()
),但不能执行Location.exits.remove('Colorado')
)我们不这样做。我们在现有列表的基础上进行新的初始化,但它不是同一个列表。this.exits是实例变量,exits是作为参数传递给构造函数的局部变量