Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/325.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 初始化自身时,为什么要传递集合(或任何对象)的引用?请检查下面的代码_Java_Collections_Immutable Collections - Fatal编程技术网

Java 初始化自身时,为什么要传递集合(或任何对象)的引用?请检查下面的代码

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,

请检查下面代码的第5行。如果我的问题错了,也请纠正

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是作为参数传递给构造函数的局部变量