Emmanuel Njorodongo
Emmanuel Njorodongo

Reputation: 1292

no instance(s) of type variable(s) K, V exist so that Map<K, V> conforms to HashMap<String, String>

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

Answers (1)

Federico klez Culloca
Federico klez Culloca

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

Related Questions