gpt4 book ai didi

Java:如何使私有(private)字段Map在类中不可变?

转载 作者:行者123 更新时间:2023-12-02 08:31:08 35 4
gpt4 key购买 nike

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

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

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

是否有另一种方法可以在不强制映射为 HashMap 的情况下实现此目的?我希望它保持与以前相同的类别。

最佳答案

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

关于Java:如何使私有(private)字段Map在类中不可变?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19125160/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com