generics - Why do we use "? super T" in java? -


this question has answer here:

for example, using when using generic comparator - comparator<? super t> c

i understand means comparator compare t , super classes, don't understand logic behind it. why not use "? extends t" ? or, example, have found similar question of asked "list<? super number>" - mean list gonna receive number objects , super classes? number's superclass object, mean list can receive object?

it doesn't mean t , super-classes. means t , sub-classes. no, list cannot receive object, can receive sub-class of number.

list<? super number> numbers = new arraylist<>(); integer = 23; double d = 3.14; object o = new object(); numbers.add(i); numbers.add(d); numbers.add(o); // compilation error 

integer , double both extend number. sub-classes of number. can added list of numbers.

number sub-class of object. if @ source code, not explicitly extend (although implement serializable). means super-class object. cannot add object numbers list.

object o2 = 300; numbers.add(o2);    // compilation error numbers.add((number) o2);   // no compilation error once cast 

in fact, can add object if number. of course, numbers objects, although not objects numbers. however, if declared object, first have cast number.


Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

css - Make div keyboard-scrollable in jQuery Mobile? -

ruby on rails - Seeing duplicate requests handled with Unicorn -