Yassine Badache
Yassine Badache

Reputation: 1851

Cannot add an object to List<?> instantiated as ArrayList<Object>

I ask this question because of a discussion about one answer here on Stack. The statement is the following:

Given the following code:

List<?> list =new ArrayList<Integer>();

Why can't we do:

Integer e = 2;
list.add(e);

This throws a compiler error, despite the fact that we instantiated the list as an ArrayList<Integer>.

Why is that ?

Upvotes: 2

Views: 127

Answers (2)

Patrick Parker
Patrick Parker

Reputation: 4959

Because a List<?> could be any sort of List (List<String> for example). And the compiler should not permit adding the wrong type to a list.

However, if you know the actual class then you can do a class cast at runtime:

((List<Integer>)list).add(e);

Code like this should be avoided since it can generate a ClassCastException if an unexpected type is encountered at runtime. To make matters worse (as noted by luk2302), our ClassCastException might only occur in an entirely different area of the code-- namely, when we are retrieving something from the list.

A better approach

If you know that the list will be of a specific type or a superclass of that type, then you could define the variable using a bounded wildcard:

List<? super Integer> list;
Integer e = 2;

list = new ArrayList<Integer>();
list.add(e);

list = new ArrayList<Number>();
list.add(e);

list = new ArrayList<Object>();
list.add(e);

This approach, as noted by M. Prokhorov, allows us to avoid the need for an inadvisable cast.

Upvotes: 4

anon
anon

Reputation: 7

Just create an Arraylist of and they will let you add all, because Integer, String and Boolean are child or in other words Object class is their parent.

Upvotes: 0

Related Questions