Originally posted by anjali ray:
The above code does not compile.
I was wondering why I am not able to add to the list?
It does have a super and I thought I could add String or a super class of String and Object being superclass of all, I should be able to add Object.
Thanks for any help
As far as my limited understanding goes, I think that:
wildcard(? notation) is used similarly as Object[].
We know that Collection can not be used polymorphically like:
Object[] arr = new Integer[10];//This is ok with array
But not:
ArrayList<Object> arrList = new ArrayList<Integer>();//Can't do this!
To overcome this. ? is used
ArrayList<?> arrList = new ArrayList<Integer>();//OK!
Now ? behaves like Object class which is supertype of all classes
? can have bounds: extends and super
These 2 work similarly except:
? extends T: the right handside can be a collection T or subtypes of T. However, you can't add anything to the collection.
? super T: the right handside can be a Collection of T or supertypes. You can add T and subtypes of T elements to the collection.
Back to this question: you can pass a Collection of String or supertypes of Strings but you can't add a supertype of String element to the collection. Hence .add(new Object()) produces compile-error