在参数中使用通用集合 [英] Using generic collections in arguments

查看:100
本文介绍了在参数中使用通用集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设您有:

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);
}

现在显然声明一个是正确的方法,编译错误在声明二。我想知道为什么Java选择以这种特定的方式强制类型安全;如果一个猫列表仍然是一个动物列表,为什么一个方法期待一个动物列表不喜欢收到一束猫?

Now obviously declaration one is the correct way to do this, and you receive a compile error on declaration two. I would like to know though why Java chooses to enforce type safety in this specific manner; if a list of Cats is still a list of Animals, why does a method expecting a list of animals balk at receiving a bunch of cats?

奇怪,比任何其他 - 并有机会更好地完善我的知识。

Curiousity, more than anything else - and a chance to better refine my knowledge.

干杯,
Dave。

Cheers, Dave.

推荐答案

Java泛型不是协变。如果你可以这样做:

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

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

那么你将能够:

x.add(new Dog());

这违反了 ArrayList< Cat> 只能保存 Cat 对象(或子类对象)。

which violates the concept that an ArrayList<Cat> can only hold Cat objects (or subclass objects).

有关详细信息,请阅读: Java理论与实践:泛型陷阱

Read this for for more details: Java theory and practice: Generics gotchas.

这篇关于在参数中使用通用集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆