How to get a immutable collection from java HashMap?

前端 未结 5 679
一个人的身影
一个人的身影 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条回答
  •  猫巷女王i
    2020-12-19 03:21

    Create a shallow copy of the original map whith HashMap.clone(), then retrieve the values colleation from that. This will create new references to the objects in the original map at the time of the clone() call; obviously changes inside the contained objects themselves will still be reflected in the copied collection. If you want this behaviour, your only way is to hard copy the map objects in your desired collection.

提交回复
热议问题