• Post Reply Bookmark Topic Watch Topic
  • New Topic

Immutability of multiple copy list.  RSS feed

 
Brendon McCullum
Ranch Hand
Posts: 37
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm going through Java docs for Convenience implementations in Collections: Javadocs

Here it's mentioned:

Immutable Multiple-Copy List

Occasionally you'll need an immutable List consisting of multiple copies of the same element. The Collections.nCopies method returns such a list. This implementation has two main uses. The first is to initialize a newly created List; for example, suppose you want an ArrayList initially consisting of 1,000 null elements. The following incantation does the trick.

List<Type> list = new ArrayList<Type>(Collections.nCopies(1000, (Type)null);

As expected, I get a list consisting of 1000 null elements. But as per the docs, this list is immutable, hence any modification to the list should not be possible. But I can easily set the value of any element in the list, and it works. Please help.
 
Mike. J. Thompson
Bartender
Posts: 689
17
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Your 'list' variable is not referencing the result of calling Collections.nCopies(...), it is referencing a new ArrayList. The constructor that takes a List will copy all of the elements from the List into the ArrayList. ArrayLists are not immutable, so 'list' is not referencing an immutable List.

Instead try:

List<Type> list = Collections.nCopies(1000, (Type)null);
 
Brendon McCullum
Ranch Hand
Posts: 37
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Mike. J Thompson, I missed this.
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!