Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 693
Colin Avatar asked Jul 29 '11 18:07

Colin


1 Answers

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.

like image 110
ColinD Avatar answered Oct 04 '22 08:10

ColinD