NavigableSet<? extends Object> doesn't mean "a set that can contain any Object". If you want that, just create a NavigableSet<Object>. What it means is "this will reference a NavigableSet of a specific type, and that type will be Object or a subclass".
So it might be a NavigableSet<Object>. Or it might be a NavigableSet<Integer>. Or it might be a NavigableSet<String>. Adding an Integer can't be guaranteed to be safe in all cases, so the compiler can't allow it. In fact, there isn't anything that can safely be added apart from null.
But NavigableSet<? super Object> means "this will reference a NavigableSet of a specific type, and that type will be Object or a superclass" *. Adding to that is safe. Generally speaking, ? extends Object is useless if you want to add elements, but can be useful when you take them out. ? super Object is the other way round.
(* as you can see, not particularly useful in this case because Object doesn't have a supertype).
Suresh KumarPandey wrote:1.NavigableSet<? extends Object> set6=new TreeSet<Integer>();
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.
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:
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>();
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.
I am not a spy. Definitely. Definitely not a spy. Not me. No way. But this tiny ad ...
Free, earth friendly heat - from the CodeRanch trailboss