Question

public class Hi {
    private final Map<String, String> map;
    public Map<String, String> getMap() {
        return map;
    }
}

I have this Hi class, and I want map to be immutable. I also need a getter. Currently, another class can modify the map from the getter. I would like to return a copy of the map to solve this problem, but Map is an interface, so does that mean I have to make the getter call:

return new HashMap<String,String>(map);

Is there another way to do it without forcing the map to be a hashmap? I would like for it to remain the same class as before.

Was it helpful?

Solution

Return Collections.unmodifiableMap(map), which provides an unmodifiable view of the Map it wraps. Quoting from the Javadocs for that method:

Returns an unmodifiable view of the specified map. This method allows modules to provide users with "read-only" access to internal maps. Query operations on the returned map "read through" to the specified map, and attempts to modify the returned map, whether direct or via its collection views, result in an UnsupportedOperationException.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top