有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java对象:如何使私有字段映射在类中不可变?

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

我有一个Hi类,我希望map是不变的。我还需要一个吸气剂。目前,另一个类可以从getter修改映射。我想返回map的副本来解决这个问题,但是map是一个接口,所以这是否意味着我必须进行getter调用:

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

有没有其他方法可以在不强制映射为hashmap的情况下执行此操作?我希望它能和以前一样


共 (2) 个答案

  1. # 2 楼答案

    返回Collections.unmodifiableMap(map),它提供了它所包装的Map的不可修改视图。引用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.