考虑这个假设的类(我在在线视频中找到的):
public class Contrived<T extends Number> extends ArrayList<T> {
List <? extends T> values;
......
}
这里的类型变量Contrived
可以接受的是Number
或 Number
的某些子类型。但该类本身继承自 ArrayList
,因此无论该类获得什么类型,都将决定 ArrayList
的类型.
现在有一个名为 values
的字段,即List<? extends T values>
。那么这是什么意思呢?
是否 list
可以容纳任何延伸的东西T
(进而扩展 Number
)。
作者:PECS (producer extends, consumer super)
规则,我只能用这个List
吗?读取元素但不添加到 list
.
constructor
将如何看起来,如果我需要传递 list of doubles or some type T
?
最佳答案
您可以有一个采用 List<T>
的构造函数或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);
}
我可以通过List<C>
进入 Contrived<B>
的构造函数.
另一种设计的构造函数对于 Contrived
是合法的可能是,采取 List<T>
:
public Contrived(List<T> values)
{
this.values = values;
}
这样的构造函数不允许 List<C>
对于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
}
关于java - Java 构造函数中的泛型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21742670/