0

I have created a list like below.

ArrayList<? extends Object> arr = new ArrayList<Object>();

what i understand by above line this is an upper bounding any element which is subclass of object can be added to the list. Now I am trying like this:

String str = new String("str");
Integer i = new Integer(4);
Object obj = new Object();
arr.add(obj);
arr.add(str);
arr.add(i);

They all are giving error.What is the problem here? But when I change it to

ArrayList<? super Object> arr = new ArrayList<Object>();

All works.It is lower bounding. Can anyone explain it to me.

GD_Java
  • 1,359
  • 6
  • 24
  • 42

2 Answers2

3

You cannot add anything into the collection except null when your collection uses wildcards with upperbounds as generic type. The reason is because you could just be adding a wrong time in your collection. For more explanation Refer This

Community
  • 1
  • 1
PermGenError
  • 45,977
  • 8
  • 87
  • 106
0

Declaration ArrayList <? extends Object> arr means that arr is an ArrayList with elements of some unknown type, and the only thing known about this unknown type is that it extends Object. Once you don't know the type of ArrayList elements, the only value you can put there is null. Putting any other value will result in error because compiler cannot verify that value you are putting into ArrayList is convertable to the (unknown) type of ArrayList elements. Event the following code will be illegal:

arr.set (0, arr.get (0));

It is illegal because from compiler's point of view arr.get (0) will return value of some unknown type, that extends object, so it will threat this like arr.set (0, (Object)arr.get (0)). But it cannot safely put value of type Object into arr because arr is not ArrayList of Object, but rather ArrayList or some unknown type that extends Object. It may be ArrayList of String or ArrayList of Integer or whatever.

Mikhail Vladimirov
  • 13,572
  • 1
  • 38
  • 40
  • then why its working? ArrayList super Object> arr = new ArrayList(); Here we also have unknown type. – GD_Java Feb 11 '13 at 13:50