Why do we pass a reference of collection (or any object) when intializing itself? Please check the code below

huangapple go评论81阅读模式
英文:

Why do we pass a reference of collection (or any object) when intializing itself? Please check the code below

问题

请检查下面代码中的第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>();
        }
    }
}
英文:

Please check line 5 of the code below. And also please correct my question if it's wrong.

public class Location {
        private final Map&lt;String, Integer&gt; exits;
        public Location(Map&lt;String, Integer&gt; exits) {
            if(exits != null) {
                this.exits = new HashMap&lt;String, Integer&gt;(exits);
            } else {
                this.exits = new HashMap&lt;String, Integer&gt;();
            }
        }
}

答案1

得分: 1

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

Location对象的创建者和Location类的用户(或者它可能实现的某个接口)在系统中往往是两个不同的组件。通过你所展示的代码片段,创建者将数据(地图)封装在Location类型的对象中,以便用户只能执行一些操作(例如location.calculateDistance()),但不能执行location.exits.remove('Colorado')这样的操作。

英文:

The idea is to encapsulate the map, allowing access to the data only through the specified in the Location class interface.

The creator of the Location object and the user of the Location class (or some interface it could implement) very often will be two different components in the system. By doing what you've shown as code snippet, the creator is encapsulating the data (the map) within an object of type Location so that the user can only do a number of things with it (e.g. location.calculateDistance()) but cannot do location.exits.remove(&#39;Colorado&#39;).

huangapple
  • 本文由 发表于 2020年10月7日 13:40:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/64237851.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定