Is this generics example from Bruce Eckel's "Thinking in Java" wrong? -
Is this generics example from Bruce Eckel's "Thinking in Java" wrong? -
i reading generics chapter in "thinking in java". programme there below.
public class genericwriting { static <t> void writeexact(list<t> list, t item) { list.add(item); } static list<apple> apples = new arraylist<apple>(); static list<fruit> fruit = new arraylist<fruit>(); static void f1() { writeexact(apples, new apple()); // writeexact(fruit, new apple()); // error:------------------line 1 // incompatible types: found fruit, required apple } static <t> void writewithwildcard(list<? super t> list, t item) { list.add(item); } static void f2() { writewithwildcard(apples, new apple()); writewithwildcard(fruit, new apple()); } public static void main(string[] args) { f1(); f2(); } }
below says "the writeexact( ) method uses exact parameter type (no wildcards). in f1( ) can see works fine—as long set apple list<apple>
. however, writeexact( ) not allow set apple list<fruit>
, though know should possible."
but when uncomment line 1 , execute it, working fine. can please help me went wrong?
however, writeexact( )
not allow set apple
list<fruit>
, though know should possible.
this incorrect. writeexact
can set apple
in list<fruit>
. <t>
inferred fruit
, apple
(presumably) subtype of fruit
.
you should check java version book written for. may in older version of java not compile due less inference on part of compiler. otherwise book contains error.
this compile of java 6+ can confirm.
java generics
Comments
Post a Comment