Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: how to make a private field Map immutable within a class?

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.

like image 620
Popcorn Avatar asked Dec 05 '25 20:12

Popcorn


1 Answers

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.

like image 146
rgettman Avatar answered Dec 08 '25 09:12

rgettman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!