Reputation: 1292
I am trying to initialize my HashMap<String, String> hashMap
in a one liner.
Below is how i am initializing my Map<String, String> map
and its just working okay
Map<String, String> map = Map.of("name", "Murife");
Below is how i am initializing my hashMap
HashMap<String, String> hashMap = Map.of("name", "Murife");
Is it possible to Initialize a HashMap using Map.of or it is only limited to Map
Upvotes: 0
Views: 2382
Reputation: 27119
Map.of
doesn't return a HashMap
, it returns an unmodifiable map (what type that is exactly is implementation-dependent and not important), so you can't assign it to a HashMap
.
You can work around that by using the HashMap
's constructor that accepts (and makes a copy of) another map as an argument.
HashMap<String, String> hashMap = new HashMap<>(Map.of("name", "Murife"));
Upvotes: 2