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

孤者浪人 提交于 2019-12-22 12:17:14

问题


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.


回答1:


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.




回答2:


Return an unmodifiableMap using the Collections API. http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Collections.html#unmodifiableMap(java.util.Map)



来源:https://stackoverflow.com/questions/19125160/java-how-to-make-a-private-field-map-immutable-within-a-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!