views:

141

answers:

7

Eclipse is saying "HashMap is a raw type" When I use the following code

HashMap = new HashMap();

Any idea what could be wrong?

+14  A: 

Eclipse will give you that warning when you use a non-Generic HashMap using Java 5 or newer.

See Also: The Generics Lesson in Sun's Java Tutorials.

Edit: Actually, here, I'll give an example too:

Say I want to map someone's name to their Person object:

Map<String, Person> map = new HashMap<String, Person>();
// The map.get method now returns a Person
// The map.put method now requires a String and a Person

These are checked at compile-time; the type information is lost at run-time due to how Java implements Generics.

R. Bemrose
map.get() still takes an Object. It might seem surprising (check the javadoc if you don't believe me), but Josh Bloch commented on this once, saying that if they had changed the signature to get(K key) they might cause errors for code that is, in fact, correct.
waxwing
@waxwing: Interesting. I should have noticed that when I looked at the Map/HashMap pages. I'll fix that. Oh, I also forgot to mention get now returns a `Person` object. Whoops.
R. Bemrose
@R. Bemrose: technically, `get` still returns `Object`, but the generics tell the compiler to add a cast to `Person`.
Brian S
@Brian: That's done internally, though. It's documented in the `Map`/`HashMap` docs as returning type `V`, unlike its argument which takes an `Object`.
R. Bemrose
+1  A: 

That is missing generics, i.e. . If you don't know thise then set the eclipse compiler to java 1.4

Thorbjørn Ravn Andersen
+2  A: 

Nothing wrong exactly, but you are missing out on the wonderful world of generics. Depending on what constraints you want to place on the types used in your map, you should add type parameters. For example:

Map<String, Integer> map = new HashMap<String, Integer>();
jjujuma
A: 

That usually means you're mixing generic code with non-generic code.

But as your example wont even compile its rather hard to tell....

Visage
+1  A: 

Try

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

instead (obviously replacing the key type (String) and value type (Integer)).

Tim
A: 

It's missing the generic type. You should specify the key-value generic pair for your map. For instance, the following is a declaration that instantiates a HashMap with String type key and Integer type value.

Map<String, Integer> map = new HashMap<String, Integer>();
S73417H
A: 

All of these are valid answers, you could also use the @SurpressWarnings annotation to get the same result, without having to resort to actual generics. ;)

mezmo