tags:

views:

1011

answers:

2

I have a legacy class that the class itself is not a generic but one of its methods return type uses generics:

public class Thing {
    public Collection<String> getStuff() { ... }
}

getStuff() uses generics to return a collection of strings. Therefore I can iterate over getStuff() and there's no need to cast the elements to a String:

Thing t = new Thing();
for (String s: t.getStuff())  // valid
{ ... }

However, if I change Thing itself to be a generic but keep everything else the same:

public class Thing<T> {
    public Collection<String> getStuff() { ... }
}

and then keep using the non-generic reference to Thing, getStuff() no longer returns Collection<String> and instead returns a non-typed Collection. Thus the client code does not compile:

Thing t = new Thing();
for (String s: t.getStuff())  // compiler complains that Object can't be cast to String
{ ... }

Why is this? What are the workarounds?

My guess is that by using a non-generic reference to a generic class, Java turns off all generics for the entire class. This is pain, because now I've broken my client code by making Thing a generic.

Edit: I'm making Thing generic for another method which is not listed in the above example code. My question is educational as to why the above cannot be done.

+6  A: 

Ok, take two, I misunderstood your question.

When you delcare Thing (this is called a raw type) instead of Thing<?> (parameterized type) the Java compiler strips out all generic arguments, even thogh (as in your case) the generic type of the method has nothing to do with the generic type of the class.

From the (excellent) Java Generics FAQ:

Can I use a raw type like any other type?

Methods or constructors of a raw type have the signature that they would have after type erasure.

This seemingly inocuous and unobtrusive sentence describes the behaviour in question. You're using Thing as a raw type so the return type is Collection (not Collection<String>) since this is the type after type erasure.

Confused? Not surprising. Just look at the size of that FAQ. There's probably about three people on earth who nderstand the full implications of Java Generics. Just consider my favourite declaration from the JDK:

Enum<T extends Enum<T>>

(Theres an explanation of that in the FAQ too).

cletus
I'm making Thing generic because of another method (not listed in my example).
Steve Kuo
If thing is Thing (and not Thing<?>), it will not compile. Go ahead and try it.
Steve Kuo
Misunderstood the question, changed.
cletus
Ok, got there in the end...
cletus
Wow. Java generics are even more of a pain than I'd realised...
Jon Skeet
@Jon: it all stems from the decision to retain backwards compatibility (type erasure). Java people find things like IEnumerable<T> and IEnumerable in C# having no relationship to each other a bit weird.
cletus
A: 

It is failing because of erasure. You can read more about it in these Java Tutorials

Ryan Ahearn