UnmodifiableMap(Java 集合)与 ImmutableMap(Google) [英] UnmodifiableMap (Java Collections) vs ImmutableMap (Google)

查看:28
本文介绍了UnmodifiableMap(Java 集合)与 ImmutableMap(Google)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

背景

我需要返回对用于数据缓存的地图的引用,并且我想确保没有人可以修改他们的引用.

I need to return a reference to a map that I'm using for a data cache, and I'd like to make sure nobody can modify their reference.

问题

我在网上看到了很多对 UnmodifiableMap 和 ImmutableMap 的引用,但我没有看到任何比较/对比它们的内容.我认为 Google/Guava 创建自己的版本是有充分理由的 - 有人能告诉我它是什么吗?

I've seen lots of references to UnmodifiableMap and ImmutableMap online, but I don't see anything comparing/contrasting them. I figure there is a good reason that Google/Guava created their own version - can someone tell me what it is?

推荐答案

不可修改的地图可能仍会更改.它只是可修改地图上的视图,通过不可修改地图可以看到支持地图的变化.不可修改的映射只会阻止那些只有不可修改视图的引用的人进行修改:

An unmodifiable map may still change. It is only a view on a modifiable map, and changes in the backing map will be visible through the unmodifiable map. The unmodifiable map only prevents modifications for those who only have the reference to the unmodifiable view:

Map<String, String> realMap = new HashMap<String, String>();
realMap.put("A", "B");

Map<String, String> unmodifiableMap = Collections.unmodifiableMap(realMap);

// This is not possible: It would throw an 
// UnsupportedOperationException
//unmodifiableMap.put("C", "D");

// This is still possible:
realMap.put("E", "F");

// The change in the "realMap" is now also visible
// in the "unmodifiableMap". So the unmodifiableMap
// has changed after it has been created.
unmodifiableMap.get("E"); // Will return "F". 

与此相反,Guava 的 ImmutableMap 确实不可变:它是给定映射的真正副本,没有人可以以任何方式修改此 ImmutableMap.

In contrast to that, the ImmutableMap of Guava is really immutable: It is a true copy of a given map, and nobody may modify this ImmutableMap in any way.

更新:

正如在评论中指出的那样,一个不可变的也可以使用标准 API 使用

As pointed out in a comment, an immutable map can also be created with the standard API using

Map<String, String> immutableMap = 
    Collections.unmodifiableMap(new LinkedHashMap<String, String>(realMap)); 

这将在给定地图的真实副本上创建一个不可修改的视图,从而很好地模拟 ImmutableMap 的特性,而无需向 Guava 添加依赖项.

This will create an unmodifiable view on a true copy of the given map, and thus nicely emulates the characteristics of the ImmutableMap without having to add the dependency to Guava.

这篇关于UnmodifiableMap(Java 集合)与 ImmutableMap(Google)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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