开发者

Does Collections.unmodifiableCollection(list) copy the collection?

private List list;

If we use Collections.unmodifiableCollection(list), will this return a copy of the collection, or is it faster than creating a copy? We could do other.addAll(list) but we have list of 600,000 object, so addAll is not so 开发者_开发问答good.

Caller just needs a read-only collection.


Collections.unmodifiableList just returns an unmodifiable wrapper; it does not copy the contents of the input list.

Its Javadoc states this fairly clearly:

Returns an unmodifiable view of the specified list. This method allows modules to provide users with "read-only" access to internal lists. Query operations on the returned list "read through" to the specified list, and attempts to modify the returned list, whether direct or via its iterator, result in an UnsupportedOperationException.

As Matt Ball mentioned, if you don't need the internal List to be mutable, you may want to just store a Guava ImmutableList internally... you can safely give that to callers directly since it can never change.


Does Collections.unmodifiableCollection(list) copy the collection?

The other answers are correct (+1s all around): the answer is no.


Instead of Collections.unmodifiableList() you can use Guava's ImmutableList.copyOf() to create an immutable (not modifiable) list copy.


Collections.unmodifiableCollection(..) simply wraps the original collection, disabling methods for modification. It doesn't copy it.

If you change the original list, the "unmodifiable" collection will also change. But the client having only the unmodifiable collection can't change it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜