您可以有一个采用 aList<T>
或 a的构造函数List<? extends T>
。继续设计类:
class B extends Number{
public double doubleValue() { return 0; }
public float floatValue() { return 0; }
public long longValue() { return 0; }
public int intValue() { return 0; }
}
class C extends B{}
我在类中添加了一个人为的、合法的构造函数Contrived
,采用List<? extends T>
:
public Contrived(List<? extends T> values)
{
this.values = values;
}
这使我可以编写main
如下方法:
public static void main(String[] args)
{
List<C> bList = Arrays.asList(new C(), new C(), new C());
Contrived<B> ci = new Contrived<B>(bList);
}
我可以将 a 传递给 aList<C>
的构造函数Contrived<B>
。
另一种合法的人为构造函数的设计Contrived
可能是,采用List<T>
:
public Contrived(List<T> values)
{
this.values = values;
}
这样的构造函数不允许 a List<C>
for a Contrived<B>
,因为现在类型必须匹配,如以下两个Contrived
示例所示:
public static void main(String[] args)
{
List<C> cList = Arrays.asList(new C(), new C(), new C());
Contrived<C> ci = new Contrived<C>(cList); // must match now
}
和
public static void main(String[] args)
{
List<B> bList = Arrays.asList(new B(), new B(), new B());
Contrived<B> ci = new Contrived<B>(bList); // must match now
}