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>();
}
}
}
The idea is to encapsulate the map, allowing access to the data only through the specified in the
Locationclass interface.The creator of the
Locationobject and the user of theLocationclass (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 typeLocationso that the user can only do a number of things with it (e.g.location.calculateDistance()) but cannot dolocation.exits.remove('Colorado').