Reputation: 149
I get a compile time error on countList method.
public static void countList( List<? extends Number> list, int count ){
for( int i = 0; i < count; i++ ){
list.set(i, i-1);
}
}
public static void clearList( List<?extends Number> list){
list.clear();
}
It says: The method set(int, capture#2-of ? extends Number) in the type List is not applicable for the arguments (int, int)
What does this error message mean? Why can't I set the elements in the list? Why is it OK to clear the list?
Upvotes: 0
Views: 131
Reputation: 23186
The problem is the compiler doesn't know what type of Number will be added to the list at runtime, because of type erasure. Consider this example:
public static void main(String[] args) {
List<Integer> intList= new ArrayList<Integer>();
// add some Integers to the list here
countList(intList, 4);
}
public static void countList( List<? extends Number> list, int count ) {
for( double d = 0.0; d < count; d++ ){
list.set((int)d, d-1); // problem at d-1, because at runtime,
// the double result of d-1 will be autoboxed to a Double,
// and now you have added a Double to an Integer List (yikes!);
}
}
Because of this, you can never add to a generically typed Collection using the ? extends SomeObject
syntax. If you must add, you can change your method declaration to:
public static void countList( List<Number> list, int count )
public static void countList( List<? super Integer> list, int count )
.Either way, the compiler will stop complaining because it can rest assured that you will never add anything into the List that is not the same type as what the List is declared as.
Upvotes: 2
Reputation: 47974
Because it's a list of "Something that extends number, but I don't know what." You can't go just putting integers in there, what if it's actually a list of doubles?
List<Double> list = new ArrayList<Double>();
list.add(Double.valueOf(4.5);
countList(list, 1);
Double d = list.get(0); //what happens here? You put an Integer in there! class cast exception
You can clear the list because for that operation it doesn't matter which subtype of Number is actually in there. clear is clear is clear.
Upvotes: 3