Java:如何在一个类中创建私有字段Map不可变? [英] Java: how to make a private field Map immutable within a class?

查看:655
本文介绍了Java:如何在一个类中创建私有字段Map不可变?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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.

推荐答案

返回 Collections.unmodifiableMap(地图),它提供了一个不可修改的 Map 视图。引用该方法的Javadocs

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


返回指定地图的不可修改视图。此方法允许
模块为用户提供对内部映射的只读访问。
对返回的地图上的查询操作读取到指定的
地图,并尝试修改返回的地图,无论是直接还是通过
其集合视图,都会导致UnsupportedOperationException。

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:如何在一个类中创建私有字段Map不可变?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆