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
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.
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.
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(...)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With