C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
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).
Tip: Many of the same methods work the same on an ImmutableList as other lists. An ImmutableList can be used in a for-loop.
ForHowever: The add() method does not work. It will cause an exception if you invoke add.
Java program that uses ImmutableList.copyOf
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);
}
}
}
Output
10
20
30
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 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);
}
}
Output
true
[cat, dog, bird]