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.
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.
However The add() method does not work. It will cause an exception if you invoke add.
import com.google.common.collect.*;
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);
}
}
}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.
Detail We also invoke the contains() method on the ImmutableList. This returns true because the argument passed exists within.
import com.google.common.collect.*;
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);
}
}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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.