1

I am trying to create a generic method which accepts a list of numbers in the format below. I know that I should be able to add any class to the list "o" which is at least a number (floats, integers, doubles) BUT also I should be able to add any object because all classes extend from object. In other words, object is a super class of any classs. So I wonder, why do I get an error on the line o.add(p); ?

public int checkType(List<? super Number> o) 
{
   Object p = new Object();
   //error
   o.add(p);
   return - 1;
 }

I followed the explanation of generics from Difference between <? super T> and <? extends T> in Java which is the accepted answer.

Community
  • 1
  • 1
george
  • 3,102
  • 5
  • 34
  • 51

2 Answers2

2

The type-parameter List<? super Number> o specifies that any List which can hold a Number can be passed to it.

Which could be List<Object>, but that could also be List<Number>.

So compiler will allow you to add only Number (or subtype) objects to it.

To test, call your methods with the following arguments.

checkType(new ArrayList<Object>()); // Works fine (and it can hold Object type).
checkType(new ArrayList<Number>()); // Works fine (But it can NOT hold Object type).

So, as you see a List<? super Number> means that you are trying to add a Number to the list (Rule of PECS).

Buhake Sindi
  • 87,898
  • 29
  • 167
  • 228
Codebender
  • 14,221
  • 7
  • 48
  • 85
  • checkType(new ArrayList()); works fine but then o.add(p); still doesn't work! – george Sep 03 '15 at 08:59
  • @george, that's the whole point of PECS... The parameter is not restricted to just `List`... But `List` also... And you cannot put an object inside a `List`.. So the compiler error... – Codebender Sep 03 '15 at 09:02
0

One consideration?

List<Object> myObjectList = Arrays.asList(1, 2, new SuperObject(), 4, 5);

Java comes standard with a utility class Arrays.

Buhake Sindi
  • 87,898
  • 29
  • 167
  • 228