How to get a immutable collection from java HashMap?

前端 未结 5 678
一个人的身影
一个人的身影 2020-12-19 02:44

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 , b

5条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-19 03:10

    The following is still valid and describes the issue observed (see the bit on what sort of copy is performed). I do not, however, provide any answer on how to perform a deep-copy.

    Instead, my suggestion, is to design the objects to be immutable, which avoids this issue entirely. In my experience this works really well for most trivial objects (that is, objects which are not "containers") and can simplify code and reasoning about it.


    From the Javadoc for HashMap.values:

    Returns a Collection view of the values contained in this map. The collection is backed by the map, so changes to the map are reflected in the collection, and vice-versa...

    Perhaps it would be beneficial to create a copy of it?

    HashMap map = ....;
    List values = new ArrayList(map.values());
    

    That, in essence, performs a shallow-copy that is "now separate". However, being a shallow copy, no clone/copy of the contained objects is performed. (See βнɛƨн Ǥʋяʋиɢ's answer if deep-copy semantics are desired: the question itself seems a little vague on the matter.)

    Happy coding

提交回复
热议问题