简体   繁体   中英

Is there any reason I shouldn't ignore generic types in the concrete types?

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? eg,

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

Google Collections to the rescue!

Use Maps.newHashMap ->

import com.google.common.collect.Maps;
Map<X, Map<Y, Z>> myAwesomeMap = Maps.newHashMap();

If you can live with the warning, it really isn't a problem.

Java 7 will support generic type inference for cases like your example, so those warnings will go away. Don't suppress the warnings, because that could mask real mistakes—cases that you believe are covered by simple type inference, but the compiler knows better.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM