Java Generics Wildcard bounding cannot set -


i have following classes.

public class basket<e> {     private e element;      public void setelement(e x) {         element = x;     }      public e getelement() {         return element;     } }  class fruit {} class apple extends fruit {} class orange extends fruit {}  

my confusion comes when consider following cases.

basket<? extends fruit> basket = new basket<>();  basket.setelement(new apple()); // cannot set 

and

basket<fruit> basket = new basket<>();  basket.setelement(new apple()); // okay! 

if ? extends fruit means can pass @ least fruit (or implements or extends), why cannot pass in apple type? cannot see difference between 2 cases if passing apple type in second case works because apple descendant of fruit...

basket<? extends fruit> not mean basket can hold object long subtype of fruit. means basket of unknown type t extending fruit. example basket<apple>, basket<orange> or basket<fruit>. because basket<orange>, can't set item apple.

basket<fruit> basket of fruit. fruit do.


Comments

Popular posts from this blog

java - Could not locate OpenAL library -

c++ - Delete matches in OpenCV (Keypoints and descriptors) -

sorting - opencl Bitonic sort with 64 bits keys -