Suresh KumarPandey wrote:1.NavigableSet<? extends Object> set6=new TreeSet<Integer>();
set6.add(new Integer(32));
why this add gives error because i am adding a integer object only which extends Object.
When declaring a reference using wildcard (?) with extends, the reference can point to anything that is a subtype of generic declaration.
Ex.:
At the example above, animals can reference a List of Dogs, or Cats (regarding that Dog and Cat extends Animal).
But it does not mean that you can use the method add from animals, because it's totally unsafe.
If
java compiler allowed that you could fall into something like this:
Creating a list of dogs and passing dogs to getMoreAnimals method:
getMoreAnimals method:
If using a reference List<? extends Animal> allowed to add things to this, the code above will add something wrong into the list.
It will be inserting a cat inside a dogs list. The compiler will think you were using an animal list.
Suresh KumarPandey wrote:2.
NavigableSet<? super Object> set5=new TreeSet<Object>();
set5.add(new Double(3.14));
Why the add method does not throw compile error here.
Second question is using super which was created to allow insertions. Not only navigating through a collection for example.
With super you can pass a list of Dogs or Animals or even Objects and can add Dogs to this. But remember, ONLY Dog can be inserted.
Consider the following example (changing the getMoreAnimals a little bit):
And you can pass a list of animals through this method:
I hope it can clarify your doubts about
polymorphism using generics.