0

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
    we don't. we base a new initialization on an existing List, but it's not the same one. this.exits is the instance variable, exits is the local variable passed as parameter to the constructor – Stultuske Oct 07 '20 at 05:53

1 Answers1

1

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').

LIvanov
  • 1,126
  • 12
  • 30