Using shared collections in arguments

Say you have:

public interface A {}

public class B implements A {}

public class C {
  void foo (List<A>) {}
}

public class Test {
  //Declaration one
  List<A> x = new List<A>();

  //Declaration two
  List<A> x = new List<B>();

  B b = new B();
  x.add(b);


  new C().foo(x);
}

Now it’s obvious that declaring is the right way to do this, and you get a compilation error for declaration two. I would like to know exactly why Java chooses to ensure type safety this way; if the list of cats is still a list of animals, why the method that expects the list of animals to stop receiving a bunch of cats?

Curiosity, more than anything, and a chance to improve my knowledge.

Cheers, Dave.

+3
source share
3 answers

Java generics are not covariant. If you can do this:

ArrayList<Animal> x = new ArrayList<Cat>();

then you can:

x.add(new Dog());

which violates the concept that ArrayList<Cat>can only contain objects Cat(or objects of a subclass).

: Java: .

+9

, , ?

, . , , :

I think there's a spy aming us ...

, , , , .

+9

"extends" :

List<? extends A>x;

, .

0

All Articles