英文:
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<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>();
}
}
}
答案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('Colorado')
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论