In Java, you can use the List.of() factory method to create an unmodifiable List consisting of specified elements. This method is available from Java 9 onwards.
Here is a simple example:
package org.kodejava.util;
import java.util.List;
public class ListOfExample {
public static void main(String[] args) {
List<String> names = List.of("Rosa", "John", "Mary", "Alice");
for (String name : names) {
System.out.println(name);
}
names.add("Bob"); // throws java.lang.UnsupportedOperationException
}
}
In the code above, we have created a list of names including “Rosa”, “John”, “Mary”, and “Alice”. This newly created list is unmodifiable, so attempting to add, update, or remove elements from it will throw an UnsupportedOperationException
.
There are several overloaded versions of the List.of()
method that each accept different numbers of arguments. The versions range from no argument (which creates an empty list) to 10 explicit arguments of type E
. Here’s an example:
List<String> a = List.of(); // An empty list
List<String> b = List.of("One"); // A list with one element
List<String> c = List.of("One", "Two"); // A list with two elements
// ...
List<String> j = List.of("One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten"); // A list with ten elements
However, if we need to create a list with more than 10 elements, we have another overloaded version of List.of()
method which accepts an array or varargs.
List<String> list = List.of("One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven");
Remember that these lists are unmodifiable. That means, if you try to modify the list (add, update, or remove elements) after they have been created, an UnsupportedOperationException
will be thrown. Also, List.of()
doesn’t allow null
elements. If you pass null
, it will throw UnsupportedOperationException
.
- How do I create a servlet filter to make secure cookies? - April 18, 2024
- How do I configure secure cookies using web.xml? - April 18, 2024
- How do I create a table with multiple header in iText 8? - March 16, 2024