0

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

Emmanuel Njorodongo
  • 1,004
  • 17
  • 35
  • Why would you need that? I guess you might want to learn about the benefits of using abstractions. See [What does it mean to "program to an interface"?](https://stackoverflow.com/questions/383947/what-does-it-mean-to-program-to-an-interface) – Alexander Ivanchenko Oct 21 '22 at 12:49
  • @AlexanderIvanchenko what if they want to later modify that map? – Federico klez Culloca Oct 21 '22 at 12:54
  • @FedericoklezCulloca if i would like to later modify the map i would just declare an empty Map and later add the items using put but thats not the point here, here i just want to use the HashMap once only thats why declaring an empty map and using put to add items to the map just makes the code a little bit longer, yeah its negligible and it might not matter to you but it does to me – Emmanuel Njorodongo Oct 23 '22 at 08:55
  • @EmmanuelNjorodongo my point was that if you did what Alexander Ivanchenko implied and simply declared `hashMap` as a map you would still have obtained an unmodifiable map from the `of` method and you couldn't add elements to it if you needed to. I was answering their "Why would you need that?" – Federico klez Culloca Oct 23 '22 at 09:16

1 Answers1

1

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"));
Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95