So I have two questions about HashMap
s in Java:
What is the correct way to initialize a HashMap
? I think it might be best in my situation to use:
HashMap x = new HashMap();
But Eclipse keeps suggesting that I use:
HashMap<something, something> map = new HashMap();
Which is better?
Can a HashMap
hold different types of objects/data types as values? For example, would this work and be OK:
map.put("one", 1); map.put("two", {1, 2}); map.put("three", "hello");
In the first put()
, I want an int
as a value, in the second an int[]
, and third a string. Is this okay to do in Java with HashMap
s? Also, is it okay to store a HashMap
as a value within a HashMap
?
Overview. A HashMap stores key-value mappings. In this tutorial, we'll discuss how to store values of different types in a HashMap.
The Static Initializer for a Static HashMapWe can also initialize the map using the double-brace syntax: Map<String, String> doubleBraceMap = new HashMap<String, String>() {{ put("key1", "value1"); put("key2", "value2"); }};
Assuming that both maps contain the same set of keys, and that you want to "combine" the values, the thing you would be looking for is a Pair class, see here for example. You simply iterate one of the maps; and retrieve values from both maps; and create a Pair; and push that in your result map.
It really depends on what kind of type safety you need. The non-generic way of doing it is best done as:
Map x = new HashMap();
Note that x
is typed as a Map
. this makes it much easier to change implementations (to a TreeMap
or a LinkedHashMap
) in the future.
You can use generics to ensure a certain level of type safety:
Map<String, Object> x = new HashMap<String, Object>();
In Java 7 and later you can do
Map<String, Object> x = new HashMap<>();
The above, while more verbose, avoids compiler warnings. In this case the content of the HashMap
can be any Object
, so that can be Integer
, int[]
, etc. which is what you are doing.
If you are still using Java 6, Guava Libraries (although it is easy enough to do yourself) has a method called newHashMap()
which avoids the need to duplicate the generic typing information when you do a new
. It infers the type from the variable declaration (this is a Java feature not available on constructors prior to Java 7).
By the way, when you add an int or other primitive, Java is autoboxing it. That means that the code is equivalent to:
x.put("one", Integer.valueOf(1));
You can certainly put a HashMap
as a value in another HashMap
, but I think there are issues if you do it recursively (that is put the HashMap
as a value in itself).
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