0

I have created an arraylist like this syntax:

List<?> obj = new ArrayList<Object>();

If I try to add a new Object or any object like String. It gives me compile error:

obj.add(new Object());

The method add(capture#1-of ?) in the type List<capture#1-of ?> is not applicable for the arguments (Object)

What are the objects I can add in obj?.

Guru
  • 56
  • 2
  • 13
Naveen
  • 661
  • 3
  • 14
  • 36
  • 2
    `List>` is a [list of unknown type](https://docs.oracle.com/javase/tutorial/extra/generics/wildcards.html), you can't add anything to it except of `null`. – Oleksandr Pyrohov Jul 15 '18 at 10:55
  • You can't add anything with a `?`. Remember **PECS** [What is PECS (Producer Extends Consumer Super)?](https://stackoverflow.com/questions/2723397/what-is-pecs-producer-extends-consumer-super). – Zabuzard Jul 15 '18 at 10:57
  • Also see [Difference between super T> and extends T> in Java](https://stackoverflow.com/questions/4343202/difference-between-super-t-and-extends-t-in-java/) for an in-depth explanation to wildcards. – Zabuzard Jul 15 '18 at 11:02
  • You want to avoid the duplication of `String`? Fine, use the diamond operator. – Johannes Kuhn Jul 15 '18 at 11:04

3 Answers3

2

You can add nothing but null in a List declared :

List<?> obj = ...

Otherwise you could break the type safety as this is legal :

List<?> anyList = ...;
List<Integer> integerList = ...;
anyList = integerList;

And this is also legal :

List<Integer> integerList = ...;
foo(integerList);

void foo(List<?> anyList) {
   ...  
}

If you could add anything in the List<?> such as a String, the list object referred by integerList would not contain not only Integer any longer.

To add any element in the List, just use the Object type :

List<Object> obj = ...
davidxxx
  • 104,693
  • 13
  • 159
  • 179
1

We can not add nothing to it(the sole exception is null) . See the tutorial:

It isn't safe to add arbitrary objects to it however:

Collection<?> c = new ArrayList<String>();

c.add(new Object()); //Compile time error

Since we don't know what the element type of c stands for, we cannot add objects to it. The add() method takes arguments of type E, the element type of the collection. When the actual type parameter is ?, it stands for some unknown type. Any parameter we pass to add would have to be a subtype of this unknown type. Since we don't know what type that is, we cannot pass anything in. The sole exception is null, which is a member of every type.

xingbin
  • 23,890
  • 7
  • 43
  • 79
1

List<?> means "It is a list, but I don't know what type of object is in the list". Even though you have declared this as a new List<Object>(), it could be reassigned to a new List<String>() (for example) later. And adding a new Object() to a List<String> is not a good idea.

In your case, you should declare it as a List<Object> rather than a List<?>.

Joe C
  • 13,953
  • 7
  • 35
  • 48