Java ImmutableList Examples

Use the ImmutableList class from Guava to create a read-only list of elements. Call copyOf.
ImmutableList. In large code bases, mutable collections pose a problem. We cannot be sure the collection is not modified in some other place.
With immutable classes, we copy a mutable collection (like ArrayList) into a separate location. No elements may be changed—not added nor removed. This is guaranteed.

Note: With immutable classes, many optimizations can also be applied. They can lead to more stable, faster programs.

Quote: [An immutable object] doesn't need to support mutation, and can make time and space savings with that assumption (ImmutableCollectionsExplained).

To begin, this program creates an ImmutableList with the ImmutableList.copyOf method. We pass in an ArrayList to copyOf. This results in a 3-element ImmutableList.ArrayList

Tip: Many of the same methods work the same on an ImmutableList as other lists. An ImmutableList can be used in a for-loop.


However: The add() method does not work. It will cause an exception if you invoke add.

Java program that uses ImmutableList.copyOf import*; import java.util.ArrayList; public class Program { public static void main(String[] args) { // Create an ArrayList. ArrayList<Integer> list = new ArrayList<>(); list.add(10); list.add(20); list.add(30); // Create an ImmutableList from the ArrayList. ImmutableList<Integer> immutable = ImmutableList.copyOf(list); // Display values in ImmutableList. for (int value : immutable) { System.out.println(value); } } } Output 10 20 30
Of example. We can create an ImmutableList directly with the of() method. Here we initialize a 3-element ImmutableList with string literal arguments.

Contains: We also invoke the contains() method on the ImmutableList. This returns true because the argument passed exists within.

Java program that uses ImmutableList.of, contains import*; public class Program { public static void main(String[] args) { // Create ImmutableList with of method. ImmutableList<String> values = ImmutableList.of("cat", "dog", "bird"); // Use contains method. System.out.println(values.contains("dog")); // ... Display elements. System.out.println(values); } } Output true [cat, dog, bird]
For simple programs, immutable collections are little advantage. They will just increase complexity. But larger code bases, where many players act on data, this changes.
Immutable classes, like ImmutableList, reduce complexity in large projects in an important way. They restrict how data may change. This makes operating upon data safer and more predictable.guava:
Dot Net Perls
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to