0

Why does

AbstractList<AbstractList<Number>> list = new Vector<Vector<Number>();

generates the following error :

Type mismatch: cannot convert from Vector<Vector<Number>> to AbstractList<AbstractList<Number>>

whereas Vector extends AbstractList?

Ankush soni
  • 1,439
  • 1
  • 15
  • 30
Florian Lavorel
  • 744
  • 2
  • 8
  • 14
  • https://docs.oracle.com/javase/tutorial/java/generics/subtyping.html – lukaslew Aug 14 '15 at 12:40
  • This is definitely a duplicate, but while I find it - consider what operations you can perform on an `AbstractList>`. You can perform `add(new ArrayList())` for example. You can't do that to a `Vector>`. – Jon Skeet Aug 14 '15 at 12:40
  • `Vector> a = new Vector>(); AbstractList> b = a; b.add(new LinkedList()); Vector c = a.get(0); // ????` – user253751 Aug 14 '15 at 12:44

2 Answers2

2

When using Java generics, you have to use ? extends AbstractList:

AbstractList<? extends AbstractList<Number>> list = new Vector<Vector<Number>>();
cahen
  • 15,807
  • 13
  • 47
  • 78
1

If you were able to do that, it would mean that you can call list.add(someAbstractList) which would be wrong because of the actual type of list: it is expecting a Vector (or a class that extends it) and not some other implementation of AbstractList.

dotvav
  • 2,808
  • 15
  • 31