On Tue, Aug 11, 2009 at 7:50 AM, Marshall Schor<m...@schor.com> wrote: > A small correction: allowing downcasting doesn't generate a warning > about unchecked casting. > > Here's a small test case in case you want to play with this: > > package generics; > > import java.util.List; > > public class TestG { > > class Box<T> { // version returning down-castable thing > <U extends T> U get() {return null;} > <U extends T> List<U> getL() {return null;} > } > > class StrictBox<T> { // version returning just type T > T get() {return null;} > List<T> getL() {return null;} > } > > Box<Number> box = new Box<Number>(); > StrictBox<Number> sbox = new StrictBox<Number>(); > > void test() { > // returning elements > Number n = box.get(); // OK > Integer n2 = box.get(); // OK > > Number sn = sbox.get(); // OK > Integer sn2 = sbox.get(); // fails > Integer sn3 = (Integer) sbox.get(); // OK > > // returning lists > List<Number> ln = box.getL(); // OK > List<Integer> ln2 = box.getL(); // OK > > List<Number> sln = sbox.getL(); // OK > List<Integer> sln2 = sbox.getL(): // fails, no fix available > } > } >
For a complete picture you should also try to implement the methods to return something other that null. For example how to you implement <U extends T> U get() such that it returns an instance of U regardless of what U is? You could only do this with a typecast. And you'd have to expectation that the typecast would actually succeed. -Adam