如何从 java HashMap 获取不可变集合? [英] How to get a immutable collection from java HashMap?

查看:26
本文介绍了如何从 java HashMap 获取不可变集合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从 java HashMap 中获取一个集合,而不需要稍后在集合中反映映射中的更改.我想使用 Collection.toArray() 来实现这一点,但它不起作用.结果 Object[] 也在发生变化(javadocs 说返回的数组将是安全的",因为此集合不维护对它的引用).有什么简单的方法可以实现吗?

I need to get a collection from the java HashMap without the changes in the map reflecting in the collection later . I wanted to use Collection.toArray() to achieve this , but its not working . The resultant Object[] is also changing (javadocs say that The returned array will be "safe" in that no references to it are maintained by this collection ) . Any simple way to achieve this?

推荐答案

单个 API 调用无法做到这一点,您需要使用深度克隆.更改原始文件时不会更改克隆文件.之前在 SO 上已经讨论过这个话题,请参阅 如何克隆 ArrayList并克隆其内容?深度克隆实用程序推荐.

Its not possible to do this with a single API call, you need to utilize deep cloning. Clones won't be changed when you make changes to the original. This topic has been discussed on SO before, see How to clone ArrayList and also clone its contents? and Deep clone utility recomendation.

这篇关于如何从 java HashMap 获取不可变集合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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