0

Consider

class MyClass{
    List<? extends Number> nums=  new ArrayList<Integer>();
    nums.add(3.14);//Compile error
}

In the error's description we have: excepted add(int, Object), found add(int,CAP#1). What's defenition of CAP#1? Why this error caused?

St.Antario
  • 26,175
  • 41
  • 130
  • 318

1 Answers1

2

This is because nums is a List<? extends Number>, so the compiler knows that it is a List of Number or some subclass of Number, but it does not know which. Therefore, you will never be allowed to add anything to such a list. Here's an example of what this means:

List<? extends Number> nums=  new ArrayList<Integer>();

and

List<? extends Number> nums=  new ArrayList<Double>();

are both valid assignments. However, if you do:

nums.add(new Integer(4));

the compiler will not accept this as it cannot be certain that nums is a List of Integer.

nitegazer2003
  • 1,193
  • 5
  • 10
  • @St.Antario: It is just something your compiler uses to internally represent the captured type variable. Basically, you see this when you have wildcards, and it represents the unknown type the wildcard represents. – newacct Sep 20 '13 at 02:09