-2

I'm learning about Wildcards and I dont think I understand the difference between List<Number> and List<? extends Number>. They say that the first is a list of Numbers only, and second is a list of Numbers or any of its subclasses. But every object of any subclass is instance of its superclass. Could anyone help me with that?

Vadim Landa
  • 2,784
  • 5
  • 23
  • 33
Rafał P
  • 252
  • 1
  • 8

1 Answers1

1

You can't do:

List<Number> list = new ArrayList<Integer>();

but you can do:

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

When would it be useful? As a parameter type of methods accepting a heterogenous list of objects in same hierarchy, which only reads from such list. That's because, you can't write anything, but null to second kind of list reference, i.e., given the 2nd declaration, you can't do: list.add(5);

Rohit Jain
  • 209,639
  • 45
  • 409
  • 525