2

I try to explain the issue in an example. I got an interface named X and an I got an class Y which implements X. Several instances of Y are collected in a List. Now here is the point i don't really understand. When I'm trying to assign this list to a collection I get an compiler error. Otherwise when I'm assigning this list to a collection it works.

List<Y> yList = new ArrayList<Y>();
// works
Collection<? extends X> coll1 = yList;
// error
Collection<X> coll2 = yList;

Could anybody explain whats the difference between those two variants and why the second one does not work.

sebastian
  • 2,427
  • 4
  • 32
  • 37

1 Answers1

1

For this you need to understand a bit more the concept of Generics.

Let's look at the following code:

List<Integer> ints = new ArrayList<Integer>();
ints.add(Integer.valueOf(1));
List<Number> numbers = ints;// This does not compile! and you will now see why:

numbers.add(new Double(2.3d));// This is valid
Integer i = ints.get(1); // This would be broken then because I expect an Integer but get a Double

This is why you need to cast your List<X> to Collection<? extends Y> meaning that the collection contains objects that extends Y but you don't know the exact type. You know you can cast to (Y) but you don't know what is the actual type in the collection and therefore, operations like add() or addAll() are not allowed.

Guillaume Polet
  • 47,259
  • 4
  • 83
  • 117