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

问题描述

请检查以下代码的第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>();
            }
        }
}

解决方法

想法是封装地图,仅允许通过Location类接口中的指定访问数据。

Location对象的创建者和Location类的用户(或它可以实现的某些接口)通常是系统中的两个不同组件。通过执行您显示为代码段的操作,创建者将数据(地图)封装在类型为Location的对象中,以便用户只能用它做很多事情(例如{{1} }),但不能执行location.calculateDistance()