2020-02-19

When to use unmodifiable?

An unmodifiable collection provides space efficiency benefits and prevents the
collection from accidentally being modified, which might cause the program to work
incorrectly. An unmodifiable collection is recommended for the following cases:

• Collections that are initialized from constants that are known when the program is
written
• Collections that are initialized at the beginning of a program from data that is
computed or is read from something such as a configuration file

Unmodifiable List Static Factory Methods

The List.of static factory methods provide a convenient way to create unmodifiable
lists.
A list is an ordered collection, where duplicate elements are allowed. Null values are
not allowed.
The syntax of these methods is:
List.of()
List.of(e1)
List.of(e1, e2) // fixed-argument form overloads up to 10 elements
List.of(elements...) // varargs form supports an arbitrary number of
elements or an array

In JDK 8:
List<String> stringList = Arrays.asList("a", "b", "c");
stringList = Collections.unmodifiableList(stringList);

In JDK 9:
List<String> stringList = List.of("a", "b", "c");

Unmodifiable Set Static Factory Methods

The Set.of static factory methods provide a convenient way to create unmodifiable
sets.
A set is a collection that does not contain duplicate elements. If a duplicate entry is
detected, then an IllegalArgumentException is thrown. Null values are not allowed.
The syntax of these methods is:
Set.of()
Set.of(e1)
Set.of(e1, e2) // fixed-argument form overloads up to 10 elements
Set.of(elements...) // varargs form supports an arbitrary number of
elements or an array

In JDK 8:
Set<String> stringSet = new HashSet<>(Arrays.asList("a", "b", "c"));
stringSet = Collections.unmodifiableSet(stringSet);

In JDK 9:
Set<String> stringSet = Set.of("a", "b", "c");

Unmodifiable Map Static Factory Methods

The Map.of and Map.ofEntries static factory methods provide a convenient way to
create unmodifiable maps.
A Map cannot contain duplicate keys. If a duplicate key is detected, then an
IllegalArgumentException is thrown. Each key is associated with one value. Null
cannot be used for either Map keys or values.
The syntax of these methods is:
Map.of()
Map.of(k1, v1)
Map.of(k1, v1, k2, v2) // fixed-argument form overloads up to 10 keyvalue pairs
Map.ofEntries(entry(k1, v1), entry(k2, v2),...)
 // varargs form supports an arbitrary number of Entry objects or an array

In JDK 8:
Map<String, Integer> stringMap = new HashMap<String, Integer>();
stringMap.put("a", 1);
stringMap.put("b", 2);
stringMap.put("c", 3);
stringMap = Collections.unmodifiableMap(stringMap);

In JDK 9:
Map<String, Integer> stringMap = Map.of("a", 1, "b", 2, "c", 3);



No comments:

Post a Comment