1
ArrayList<Integer> arr = new ArrayList<>();
ArrayList<Double> doub = new ArrayList<>();
        arr.add(5);
        arr.add(6);
        arr.add(7);
        doub.add(6.5);
        doub.add(8.5);
        doub.add(7.5);
        calc_test(arr);
        calc_test(doub);

public static void calc_test(List<Number> list) {
        for (Number obj : list) {
            System.out.println(obj + "");
        }
    }

I know this is an error in java and can be corrected by adding ? extends Number in the function parameter, but why does the normal way not work? After all double and integer are a type of number and a list of those types should still be a type of number, so why is that an error?

Irina Avram
  • 1,492
  • 2
  • 20
  • 35
Jude Fernandes
  • 7,437
  • 11
  • 53
  • 90

1 Answers1

1

Double and Integer is subclass of Number but ArrayList<Double> and ArrayList<Integer> are not subclass of ArrayList<Number>. For more detail here

Vaseph
  • 704
  • 1
  • 8
  • 20