views:

4701

answers:

7

So I have 2 questions about HashMaps in Java:

(1) 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?

(2) 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 HashMaps? Also, is it okay to store a HashMap as a value within a HashMap?

+4  A: 

Eclipse is recommending that you declare the type of the HashMap because that enforces some type safety. Of course, it sounds like you're trying to avoid type safety from your second part.

If you want to do the latter, try declaring map as HashMap<String,Object>.

Paul Tomblin
is an int considered an object..?
hatorade
"int"s are not objects, it's a primitive type. All the primitives (int, double, long, short...) have an object version you can use (Integer, Double, Long, Short). Java 1.5+ will even do the conversion between int and Integer for you so you don't have to worry about it (most of the time, look up "autoboxing").
MBCook
autoboxing will convert int[] into an Object.
Paul Tomblin
int[] is already an Object; surely you meant single `int` variable
ChssPly76
+1  A: 

A HashMap can hold any object as a value, even if it is another HashMap. Eclipse is suggesting that you declare the types because that is the recommended practice for Collections. under Java 5. You are free to ignore Eclipse's suggestions.

Under Java 5, an int (or any primitive type) will be autoboxed into an Integer (or other corresponding type) when you add it to a collection. Be careful with this though, as there are some catches to using autoboxing.

Ken Liu
+7  A: 

This is a change made with Java 1.5. What you list first is the old way, the second is the new way.

By using HashMap you can do things like:

HashMap<String, Doohickey> ourMap = new HashMap<String, Doohickey>();

....

Doohickey result = ourMap.get("bob");

If you didn't have the types on the map, you'd have to do this:

Doohickey result = (Doohickey) ourMap.get("bob");

It's really very useful. It helps you catch bugs and avoid writing all sorts of extra casts. It was one of my favorite features of 1.5 (and newer).

You can still put multiple things in the map, just specify it as Map, then you can put any object in (a String, another Map, and Integer, and three MyObjects if you are so inclined).

MBCook
You've had me up until the last paragraph. "lists with little 'l'" are called arrays; and they are most definitely objects in Java.
ChssPly76
You mention that to put multiple things in the map, I should just specify it as a Map. Why couldn't I use HashMap?
hatorade
@ChssPly76: "arrays". That's the term. I couldn't remember it and went with my best guess at the moment. Thanks.
MBCook
@hatorade: What I meant was just use Map instead of Map<String, Integer>. If you leave off the types the map will hold, you get basically Map<Object, Object>. You can use any kind of Map you'd like (HashMap, TreeMap, MyCustomMap, etc.).
MBCook
+12  A: 

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>();

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.

Google Collections (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).

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).

Yishai
+1, great answer. :)
Emil H
what is the difference between making a HashMap<String, Object> map = new... and Map<String, Object> map = new...? Or do they make the same thing?
hatorade
They make the same thing, it is just that your reference is typed as a Map (the interface) instead of the HashMap (the implementation) so that the implementation can be easily changed without affecting more than one line of code.
Yishai
A: 

In answer to your second question: Yes a HashMap can hold different types of objects. Whether that's a good idea or not depends on the problem you're trying to solve.

That said, your example won't work. The int value is not an Object. You have to use the Integer wrapper class to store an int value in a HashMap

Luke
In Java 5+, the compiler will do that for you.
Yishai
It'll work in Java 5, which he's using since he's getting warnings about not having parameterized the map, with autoboxing.
ColinD
+1  A: 

The way you're writing it is equivalent to

HashMap<Object, Object> map = new HashMap<Object, Object>();

What goes inside the brackets is you communicating to the compiler what you're going to put in the HashMap so that it can do error checking for you. If Object, Object is what you actually want (probably not) you should explicitly declare it. In general you should be as explicit as you can with the declaration to facilitate error checking by the compiler. What you've described should probably be declared like this:

HashMap<String, Object> map = new HashMap<String, Object>();

That way you at least declare that your keys are going to be strings, but your values can be anything. Just remember to use a cast when you get a value back out.

Graphics Noob
+1  A: 

The 2nd one is using generics which came in with Java 1.5. It will reduce the number of casts in your code & can help you catch errors at compiletime instead of runtime. That said, it depends on what you are coding. A quick & dirty map to hold a few objects of various types doesn't need generics. But if the map is holding objects all descending from a type other than Object, it can be worth it.

The prior poster is incorrect about the array in a map. An array is actually an object, so it is a valid value.

Map<String,Object> map = new HashMap<String,Object>();
map.put("one",1); // autoboxed to an object
map.put("two", new int[]{1,2} ); // array of ints is an object
map.put("three","hello"); // string is an object

Also, since HashMap is an object, it can also be a value in a HashMap.

Wayne Young