Guava ImmutableList.copyOf() method in Java
In this post, we will see how to use Guava’s ImmutableList.copyOf() method in Java to create immutable lists from various sources. We will also compare it with other methods and explained why it is superior.
As a Java developer, you may have encountered situations where you need to create an immutable list from an existing collection, array, or iterator. However, creating immutable lists in Java can be cumbersome and verbose. Guava library provides an easy way to create immutable lists in Java using the ImmutableList class.
1. Overview of ImmutableList.copyOf() method
The ImmutableList.copyOf() method is a static factory method that returns an immutable list containing the elements of the specified collection, array, or iterator. It accepts any Iterable, Collection, List, Set, or array as an argument and copies its elements into a new immutable list. It also accepts an Iterator as an argument and consumes its elements into a new immutable list. It has the following features:
- The
ImmutableList.copyOf()method guarantees that the returned list is immutable, meaning that it cannot be modified in any way. Any attempt to add, remove, or update elements in the list will result in anUnsupportedOperationException. TheImmutableList.copyOf()method also guarantees that the returned list does not contain anynullvalues. Any attempt to create an immutable list with anullelement will result in aNullPointerException. - The
ImmutableList.copyOf()method preserves the order of the elements in the original source. If the source is a List or an array, the returned list will have the same order as the source. If the source is a Set or an Iterator, the returned list will have an arbitrary but consistent order. - The
ImmutableList.copyOf()method performs defensive copying of the source elements. This means that it creates a new list object that is independent of the source object. Any changes to the source object after callingImmutableList.copyOf()will not affect the returned list.
2. Usage of ImmutableList.copyOf() method
These are some of the different versions of the Guava ImmutableList.copyOf() method that can create immutable lists from various types of parameters.
ImmutableList.copyOf(E[] elements): This method returns an immutable list containing the elements of the specified array, in the order they appear in the array.ImmutableList.copyOf(Iterable<? extends E> elements): This method returns an immutable list containing the elements of the specified iterable, in the order they are returned by the iterable.ImmutableList.copyOf(Collection<? extends E> elements): This method returns an immutable list containing the elements of the specified collection, in the order they appear in the collection.ImmutableList.copyOf(Iterator<? extends E> elements): This method returns an immutable list containing the elements of the specified iterator, in the order they are returned by the iterator.
To use ImmutableList.copyOf(), you need to add Guava as a dependency to your Java project. Once you have added Guava as a dependency, you can import the ImmutableList class from com.google.common.collect package. Then you can use ImmutableList.copyOf() to create immutable lists from various sources. Here are some examples:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
import com.google.common.collect.ImmutableList; import java.util.*; class Main { public static void main(String[] args) { // Create an immutable list from an existing list List<String> names = Arrays.asList("Andrew", "Thomas", "Isabella"); ImmutableList<String> immutableNames = ImmutableList.copyOf(names); System.out.println(immutableNames); // [Andrew, Thomas, Isabella] // Create an immutable list from an existing set Set<Integer> numbers = new HashSet<>(Arrays.asList(1, 2, 3)); ImmutableList<Integer> immutableNumbers = ImmutableList.copyOf(numbers); System.out.println(immutableNumbers); // [1, 2, 3] // Create an immutable list from an existing array String[] colors = {"red", "green", "blue"}; ImmutableList<String> immutableColors = ImmutableList.copyOf(colors); System.out.println(immutableColors); // [red, green, blue] // Create an immutable list from an existing iterator Iterator<Double> scores = Arrays.asList(9.5, 8.0, 7.5).iterator(); ImmutableList<Double> immutableScores = ImmutableList.copyOf(scores); System.out.println(immutableScores); // [9.5, 8.0, 7.5] } } |
3. Comparing ImmutableList.copyOf() with other methods
As we mentioned earlier, there are other ways to create immutable lists in Java, such as using Collections.unmodifiableList() or List.of(). However, ImmutableList.copyOf() has some advantages over these methods. Here are some of the main differences and benefits of using ImmutableList.copyOf():
Collections.unmodifiableList()does not create a new list object, but returns a view of the original list that cannot be modified. This means that the original list can still be modified by other references, and the changes will be reflected in the unmodifiable view. This can lead to unexpected and inconsistent behavior.ImmutableList.copyOf(), on the other hand, creates a new list object that is independent of the original list and cannot be modified by any reference.Collections.unmodifiableList()does not guarantee that the original list does not contain anynullvalues. If the original list contains anullvalue, the unmodifiable view will also contain anullvalue, which can cause problems when iterating or accessing elements.ImmutableList.copyOf(), on the other hand, guarantees that the returned list does not contain anynullvalues and throws aNullPointerExceptionif the source contains anullvalue.Collections.unmodifiableList()does not perform any optimizations to avoid unnecessary copying and memory allocation. It always creates a new wrapper object around the original list, regardless of its size or type.ImmutableList.copyOf(), on the other hand, performs some optimizations to avoid unnecessary copying and memory allocation.List.of()creates a new immutable list with the given elements, but does not accept collections as arguments. This means that you cannot create an immutable list from an existing collection, array, or iterator usingList.of(). You have to either convert the source to an array first, or use a stream to collect the elements into a list.ImmutableList.copyOf(), on the other hand, accepts any Iterable, Collection, List, Set, array, or Iterator as an argument and copies its elements into a new immutable list.
That’s all about Guava ImmutableList.copyOf() method in Java. For more information about this method, you can check out the Guava official documentation or its GitHub repository.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)