为什么我不允许这样做?
public abstract class A {}
public class B extends A {}
...
public ArrayList<A> foo()
{
return new ArrayList<B>();
}
Run Code Online (Sandbox Code Playgroud)
我改变了公开,因为有这么多人喜欢指出愚蠢的错误.
为什么我要编写所有这些代码.只是为了满足Java的无意义?
public List<A> foo()
{
List<A> aList = new ArrayList<A>();
List<B> bList = new ArrayList<B>();
/* fill bList*/
for (B b : bList)
{
aList.add(b);
}
return aList;
}
Run Code Online (Sandbox Code Playgroud)
Jon*_*eet 13
一个ArrayList<B>
不是ArrayList<A>
.例如,您无法在其中添加任意A
内容.或者我喜欢这样想:一堆香蕉不是水果碗.当你尝试将苹果添加到一堆香蕉中时,它会滚落下来......
您可以使用通配符使其工作:
public ArrayList<? extends A> foo()
{
return new ArrayList<B>();
}
Run Code Online (Sandbox Code Playgroud)
有关更多详细信息,请参阅Java Generics FAQ.
编辑:回答你为什么需要编写所有额外代码的具体问题:你没有.只需创建一个ArrayList<A>
内部foo()
即可开始.无需将一个列表的内容复制到另一个列表.
如果您仍然反对Java的行为,您希望使用以下代码实现什么?
// Doesn't compile, fortunately...
List<String> strings = new List<String>();
List<Object> objects = strings;
objects.add(new Date());
String string = strings.get(0); // Um, it's a Date, not a String...
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3915 次 |
最近记录: |