John Brooks
John Brooks

Reputation: 57

Generics Object assignment in java

I am getting compilation error for following code . ? means accepts any type of thing we assigned. I have Object type and passes Object type. But I am getting compilation error why ?

NavigableSet<?> set = new TreeSet<Object>();
set.add(new Object());

Upvotes: 4

Views: 1067

Answers (4)

When you declare NavigableSet<?> set then your method add looks like add(? arg). Java can not retrieve the type form ?.

This is related to principle PECS

And to solve it just use super as wildcard.

NavigableSet<? super Object> set = new TreeSet<>();

Upvotes: 0

Bohemian
Bohemian

Reputation: 425033

For the variable NavigableSet<?> , the compiler only knows that it's a NavigableSet, but doesn't know the type, so no object is safe to add.

For example, this could be the code:

NavigableSet<?> set = new TreeSet<String>(); // ? could be String
set.add(new Object()); // can't add Object to a Set<String>

Upvotes: 4

christopher
christopher

Reputation: 27346

The type is not knowable at compile time, for type ?. We use ? when the method does not depend on the type. Because the add method depends on the type, ? is not a good fit for this.

The Java compiler will attempt to find a method signature that matches the method name, the number and type of the arguments provided. So let's do the same with yours.

name: add
number of arguments: 1
type: ? // Your issue.

However, NavigableSet does not have a method that matches this criteria, hence why no method is found.

Upvotes: 0

fluminis
fluminis

Reputation: 4059

You loose the concrete type of your variable using <?> so the add can't work.

So you need to write:

NavigableSet<Object> set = new TreeSet<Object>();
set.add(new Object());

Upvotes: 0

Related Questions