6

In general I try to avoid using raw types in the signature of methods in the libraries I develop. However, lately I am starting to relax this (self-adopted) rule-of-thumb, and I am starting to write raw types more often than before.

For example, assuming a method receiving any list as parameter (i.e., the type of the list members is not important), I was tempted before to declare it as:

void myMethod(List<?> list) {...}

But now I am starting to write more and more:

void myMethod(List list) {...}

Because it is shorter.

My concrete question is: In the scenario where type parameters are not important, is using raw types in method parameters considered a good practice ? If not, why not ?

The only problem I see is being condemned to see an eternal warning in the IDE I use (although probably that can be deactivated somewhere), but I would like to be sure I am not missing something else.

Update:

Got fully convinced I should use generics everywhere after reading the paragraph below here:

Use of raw types is discouraged. The Java Language Specification even states that it is possible that future versions of the Java programming language will disallow the use of raw types.

2
  • 1
    you can use List<?> or void <T> myMethod(List<T> list) to avoid the raw type Dec 3, 2013 at 21:52
  • Hi @ratchetfreak I have just updated the question.
    – Sergio
    Dec 3, 2013 at 21:54

1 Answer 1

16

Yes, you are. Generic wildcards enforce that the container contains "something, but we're not sure what" and raw types are just "the container contains objects".

So you can get some counterintuitive results,

List<?> wild = new ArrayList<String>();
List    raw  = new ArrayList<String>();
wild.add(1); // Compile time error
raw.add(1);
raw.add("Foo");
wild.add("string"); // Still a compile time error

Wild cards are represented as the same as raw at run time, but they are typechecked to make sure you never do something silly, like adding random objects to it.

So if you don't care about type safety, then yes, you can go ahead and use List, but for 3 characters, I'd just use the parameterized type.

1
  • 3
    I agree: not only does the bare minimum <?> avoid certain logic errors, it more clearly communicates your intent. List<?> means "give me a list, any list. I don't care what is in it, I only need to call non-generic methods on it or get its contents as Object." While List means "give me a list, but I won't tell you what I'm doing with it and I might use it in a way that breaks."
    – user22815
    Dec 4, 2013 at 2:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.