Creating Immutable Lists in Java


Use Collections.unmodifiableList to create an immutable list from an existing list.

Source Code

List immutableList = Collections.unmodifiableList(new ArrayList(Arrays.asList("Apple", "Banana", "Cherry")));
// immutableList.add("Durian"); // This line would throw an UnsupportedOperationException
System.out.println(immutableList);
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments