简体   繁体   中英

Should I use question mark type argument or suppress rawtypes warning?

Since the introduction of generic type parameters (or type arguments) in Java, writing the following line in Eclipse IDE will show a yellow squiggly line on the type Class :

Class myClass;

The warning shown on a mouseover is the following, with the two options (among others):

Class is a raw type. References to the generic type Class<T> should be parameterized.

  • Add type arguments to ' Class '
  • Add @SuppressWarnings ' rawtypes ' to ' myClass '

The first option produces this code:

Class<?> myClass;

The second one produces this:

@SuppressWarnings("rawtypes")
Class myClass;

Both of the above options are equally adequate in taking care of the warning.

Assuming neither we nor Eclipse can infer generic type arguments*; what is the better approach to take, in what situations, and why?

* (despite having the option to try to do so)

A general rule every programmer should adhere to: never suppress warnings for no good reason. If you suppress a warning, you should know why the warning occurs and why it does not present a problem in your case.

In this case the reason to suppress a rawtype warning would be to support legacy code that was written in a time when genericity did not exist in Java (See the Java Language Specification 4.8):

The use of raw types is allowed only as a concession to compatibility of legacy code. The use of raw types in code written after the introduction of genericity into the Java programming language is strongly discouraged. It is possible that future versions of the Java programming language will disallow the use of raw types.

So it does not apply to your case, you should not suppress this warning.

As to the Wildcard ? , this should only be used if you want to assign various types to that variable.

For example a List<?> mylist lets you store any type in the list, while List<? extends Collection> List<? extends Collection> lets you store any type that inherits from Collection to be stored in the list. A general rule is to be as specific about allowed types as possible. This way the compiler can notify you sonner if you accidentally add an object into a List that is not meant for it.

So the best way to go here is to think about how you want to use your myClass variable and if you can make a statement about which type of objects it will hold, replace the Wildcard with that type.

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