Alex Rivera | Logout

Generics in Collection

Asked 2012-09-24T14:28:24.797
15

Here is my program. I am not sure why I am getting a compile time error.

import java.util.ArrayList;
import java.util.List;

public class Test {
public static void main(String[] args) {
    List< ? extends Number > list = new ArrayList<Integer>();

    list.add(6); // Compile Time Error

    System.out.println(list);

  }
}

But the following program works fine

import java.util.ArrayList;
import java.util.List;

public class Test {
public static void main(String[] args) {
    List< ? super Number > list = new ArrayList<Number>();

    list.add(6); 

    System.out.println(list);

    }
}

Error from Eclipse:

Here is the error description from Eclipse:

The method add(int, capture#1-of ? extends Number) in the type List is not applicable for the arguments (int)

Edit
Report

1 Answer

0

This doesn't work:

List< ? extends Number > list = new ArrayList<Integer>();
list.add(6); // Compile Time Error

because if it did you could arrive in a situation like this.

class Apple extends Number  {}

List< ? extends Number > list = new ArrayList<Integer>();
list.add(new Apple()); //if it were to work, you'd have apples in what you'd think was a list of integers
answered 2012-09-24T14:46:32.640

Your Answer