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

查看:160
本文介绍了如何从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天全站免登陆