4

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());
sp00m
  • 47,968
  • 31
  • 142
  • 252
  • @Sanjeev> The method add(capture#1-of ?) in the type Set is not applicable for the arguments (Object) – Mohsen Kamrani Apr 25 '14 at 13:09
  • possible duplicate of [How do generics of generics work?](http://stackoverflow.com/questions/16449799/how-do-generics-of-generics-work) – Dirk Apr 25 '14 at 13:10
  • it means you cannot add anything to the set but you would be able to read from it. read java generics – vikeng21 Apr 25 '14 at 13:15

4 Answers4

4

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>
Bohemian
  • 412,405
  • 93
  • 575
  • 722
0

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());
fluminis
  • 3,575
  • 4
  • 34
  • 47
0

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<>();

Community
  • 1
  • 1
0

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.

christopher
  • 26,815
  • 5
  • 55
  • 89