Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can the Object class really be a lower bound?

Tags:

java

generics

Why is the following legal when String & Integer are not super classes of Object ?

List<? super Object> mylist = new ArrayList<Object>();
mylist.add("Java"); // no compile error
mylist.add(2);

I'm aware that wild card guidelines use lower bounded wild cards and super for 'out' variables but it seems that Object doesn't function as a 'lower bound' in this case.

Also is this the only way to allow addition of any type into a list ?

like image 325
Sridhar Avatar asked Dec 27 '22 19:12

Sridhar


1 Answers

It's really simple. Remember that in Java, an instance of a subtype is also an instance of its supertypes.

Look at the signature of add

public boolean add(E e)

That means whatever you pass something whose type is E or any subtype of E.

You have a List<? super Object>. So you can pass to myList.add() anything whose type is ? super Object (an unknown type which could be Object or supertype thereof) or any subtype thereof.

Is Integer a subtype of all types contained by ? super Object? Of course. Integer is a subtype of Object, which is a subtype of all types contained by ? super Object (of course, in this case, only Object satisfies this).

You're confusing the type parameter with the things you can pass to methods. The type argument of List<? super Object> is an unknown type that is a supertype of Object, so Integer or String cannot be the actual type parameter. In fact, in this case the only valid actual type argument would be Object. But what you're asking when you pass something to the method is, is the thing I'm passing a subtype? And the answer is yes.

like image 193
newacct Avatar answered Jan 12 '23 01:01

newacct