📅  最后修改于: 2023-12-03 15:31:35.540000             🧑  作者: Mango
In Java 9, factory methods have been introduced for creating unmodifiable lists, sets, maps, and other collections. These factory methods are defined in the respective classes, and they return an unmodifiable instance of the collection. This means that the collection cannot be changed once it has been created, which makes it safer to use in multi-threaded environments.
To create an unmodifiable list, you can use the List.of()
factory method. Here's an example:
List<String> list = List.of("foo", "bar", "baz");
In this example, list
is an unmodifiable list containing the strings "foo", "bar", and "baz". If you try to add or remove elements from this list, you'll get an UnsupportedOperationException
.
To create an unmodifiable set, you can use the Set.of()
factory method. Here's an example:
Set<String> set = Set.of("foo", "bar", "baz");
In this example, set
is an unmodifiable set containing the strings "foo", "bar", and "baz". If you try to add or remove elements from this set, you'll get an UnsupportedOperationException
.
To create an unmodifiable map, you can use the Map.of()
factory method. Here's an example:
Map<String, Integer> map = Map.of("foo", 1, "bar", 2, "baz", 3);
In this example, map
is an unmodifiable map containing the keys "foo", "bar", and "baz", with corresponding values of 1, 2, and 3. If you try to add or remove entries from this map, you'll get an UnsupportedOperationException
.
All of the factory methods shown above support varargs, which means you can create a collection with any number of elements. Here's an example:
List<Integer> list = List.of(1, 2, 3, 4, 5);
In this example, list
is an unmodifiable list containing the integers 1 through 5.
Factory methods provide a convenient and safe way to create unmodifiable collections in Java 9. They are easy to use and readily available in the respective collection classes. With factory methods, you can create unmodifiable collections with just one line of code, which saves time and reduces the chances of errors.