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

42 Views Asked by At

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

There are 1 best solutions below

0
On

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