java generic class & wildcards -


i have box generic class following feature:

  • one of 2 put methods should allow client insert box , content current box.

i want method 2 types of boxes: box<number> , box<integer>, why changed put(box<t>) method put(box<? extends number> box). compilation warning. doing wrong here?

this current code: warning is: type safety: unchecked cast capture#1-of ? extends number t

public class box<t> {     public t get() {         return element;     }      public void put(t element) {         this.element = element;     }      public void put(box<? extends number> box) {         put((t) box.get()); // warning     }      private t element; }  public class boxclient {      public static void main(string[] args) {         box<number> nbox = new box<number>();         box<integer> ibox = new box<integer>();         nbox.put(ibox);      }  } 

your class box defines generic type t. t can anything. i.e. "a box containing any kind of object"

then, method receives box<? extends number>. i.e. "a box containing type of number".

the problem in method:

public void put(box<? extends number> box) {     put(box.get()); } 

the method receives "a box containing number", however, cast t. remember, t can anything, can potentially perform cast isn't number. consider example:

public class boxclient {      public static void main(string[] args) {         box<string> sbox = new box<string>();         box<integer> ibox = new box<integer>();          ibox.put(1);         sbox.put(ibox);          system.out.println(sbox.get());      }   } 

here, created box<string> or "a box containing strings" , added box<integer> or "a box containing number". generics code, valid since t can anything, however, if try execute it

java.lang.classcastexception: java.lang.integer cannot cast java.lang.string

that's because integer 1 cannot cast string.

to make sure never happen, need change declaration of box enforce t extends number, below:

public class box<t extends number> {     public t get() {         return element;     }       public void put(t element) {         this.element = element;     }      public void put(box<? extends t> box) {         put((t) box.get());     }      private t element; } 

update: mentioned, previous answer still unsafe. say, if have box<number> , try add box<integer>, still allowed , still throw exception.

best solution add bayou.io's suggestion well. way ensure that: 1: box contains numbers 2: box can add other box extends t

update2: mentioned below in comments newacct, cast t not necessary.

hope helps!


Comments