Important Notice: Our web hosting provider recently started charging us for additional visits, which was unexpected. In response, we're seeking donations. Depending on the situation, we may explore different monetization options for our Community and Expert Contributors. It's crucial to provide more returns for their expertise and offer more Expert Validated Answers or AI Validated Answers. Learn more about our hosting issue here.

How can I create an immutable List consisting of n Copies of an Object?

0
10 Posted

How can I create an immutable List consisting of n Copies of an Object?

0
10

Location: http://www.jguru.com/faq/view.jsp?EID=1262461 Created: Sep 14, 2005 Author: Brandon Rohlfs (http://www.jguru.com/guru/viewbio.jsp?EID=1245666) nCopies(int n, T o) can be used to create an immutable List which contains a specific number of copies of an Object. Care must be taken when trying to add elements to or extract elements from the returned List. Both attempts will throw UnsupportedOperationExceptions. public static List nCopies(int n, T o) import java.util.List; import java.util.Collections; public class NCopiesTest{ public static void main(String[] args){ List slist = Collections.nCopies(5, “Java Blend”); //immutable list! slist.add(“Moca Blend”); // throws UnsupportedOperationException! String selement = slist.remove(0); // throws UnsupportedOperationException!

Related Questions

What is your question?

*Sadly, we had to bring back ads too. Hopefully more targeted.

Experts123