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.