Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create mutable collections (Map.of and List.of)

Tags:

java

Looks like Map.of() and List.of() both create immutable collections. That's useful, but I am looking for a way to create mutable collections sometimes using a factory method.

When I try: HashMap.of() I get this error:

Static method may be invoked on containing interface class only

like image 907
Alexander Mills Avatar asked Mar 02 '19 21:03

Alexander Mills


People also ask

How do you make a Map mutable?

Mutable Empty Map We can simply use the HashMap constructor, which constructs an empty resizable-array implementation of the Map interface. The following code takes advantage of the new “diamond” syntax introduced in Java SE 7. Guava's Maps. newHashMap() creates a mutable, empty HashMap instance.

Is Map mutable or immutable?

There are two kinds of Maps, the immutable and the mutable. The difference between mutable and immutable objects is that when an object is immutable, the object itself can't be changed. By default, Scala uses the immutable Map.


1 Answers

HashMap has a constructor that can take another Map, so you can create a HashMap by passing it whatever Map.of(...) produces:

HashMap<String, String> map = new HashMap<>(Map.of("k1", "v1", "k2", "v2"));

Likewise for ArrayList and List.of(...).

like image 185
Jesper Avatar answered Sep 18 '22 17:09

Jesper