Generics Assigning objects in java

I get a compilation error for the following code.? means acceptance of any item that we have designated. I have an object type and pass an object type. But why am I getting a compilation error?

NavigableSet<?> set = new TreeSet<Object>();
set.add(new Object());
+4
source share
4 answers

For a variable, the NavigableSet<?>compiler only knows that it is a NavigableSet, but does not know this type, so you cannot add any objects.

For example, it could be a code:

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

You are losing a specific type of your variable with <?>, so adding cannot work.

So you need to write:

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

NavigableSet<?> set, add add(? arg). Java ?.

PECS

super .

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

0

, ?. ?, . add , ? .

Java , , . .

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

NavigableSet , , .

0
source

Source: https://habr.com/ru/post/1538071/


All Articles