tags:

views:

91

answers:

4

Generics in Java is noisy sometimes. The parameterized types are thrown out by the compiler anyway after compile, so my question is, is there really any drawbacks in ignoring them, as long as I declare the type of the reference to include parameterized types? e.g.,

Map<String, Map<Integer, String>> myMap = new HashMap<String, Map<Integer,String>>();

is just too noisy. What if I write:

@SuppressWarnings("unchecked")
Map<String, Map<Integer, String>> myMap = new HashMap();

It's so much clearer, except that Eclipse will put a disgusting wavy line under it. Put @SuppressWarning will make Eclipse happy, but many people (including me) don't like to sprinkle @SuppressWarning in the code. Is it really that bad to ignore the type parameters in "new HashMap()"?

+7  A: 

Google Collections to the rescue!

Use Maps.newHashMap ->

import com.google.common.collect.Maps;
Map<X, Map<Y, Z>> myAwesomeMap = Maps.newHashMap();
Steven Schlansker
Yes I'm aware of Guava library, but I'm just wondering what's the benefit of explicitly typing the parameterized types after "new HashMap" or what's the harm of not doing so.
EnToutCas
I think that's doing exactly the same thing as the OP asked, though?
Dean J
Nice remark but to me it's not an answer to the question.
Andreas_D
Ultimately there's no problem with suppressing warnings, except that it can accidentally suppress warnings that you didn't intend it to, and you'll run into ClassCastExceptions in strange places. I think you're right that this particular setup is "safe," but I'd still prefer "doing it right"
Steven Schlansker
+1  A: 

I think in this case you are fine. You have no choice but to refer to myMap as a Map<String, Map<Integer, String>> after this line, so type safety is preserved. You correctly noted that the type parameters are purely a compile-time construct, so all you would need to worry about is something compiling that shouldn't. You are still receiving the benefits of generics, so I don't see a problem (other than the ugly annotation).

Google Collections also provides methods to avoid having to rewrite type parameters when creating collections.

danben
+4  A: 
erickson
+2  A: 

I think that having compiler warnings but ignoring them makes them useless. Having supresswarnings is fine in theory, but it can be abused, so it can be a bad habit. This will be fixed in Java 7, where the syntax will be:

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

Until then, Google collections does it for you, but it is too simple to do yourself to get the library for that reason:

 public static <K, V> HashMap<K, V> newHashMap() {
     return new HashMap<K, V>();
 }
Yishai