Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java中的接口数组_Java_Arrays_Interface - Fatal编程技术网

Java中的接口数组

Java中的接口数组,java,arrays,interface,Java,Arrays,Interface,我有一个接口A: interface A { } 然后我有一个B班: class B implements A { } 然后我有一个方法,它使用一个列表: void process(ArrayList<A> myList) { } void进程(ArrayList myList){ } 我想给它一个B的列表: ArrayList<B> items = new ArrayList<B>(); items.add(new B()); process(ite

我有一个接口A:

interface A {
}
然后我有一个B班:

class B implements A {
}
然后我有一个方法,它使用一个列表:

void process(ArrayList<A> myList) {
}
void进程(ArrayList myList){
}
我想给它一个B的列表:

ArrayList<B> items = new ArrayList<B>();
items.add(new B());
process(items);
ArrayList items=new ArrayList();
添加(新B());
过程(项目);

但是,还有一个类型不匹配的错误。我明白为什么
ArrayList
本身就是一种类型,它没有从
ArrayList
转换为
ArrayList
的功能。是否有一种快速且资源明智的方法来形成适合传递给我的
过程
方法的新数组?

我认为最简单的解决方案是将其中一种方法更改为:

void process(ArrayList<? extends A> myList) {
}

void流程(ArrayList另一种选择是只创建
A
的ArrayList,而不是
B

ArrayList<A> items = new ArrayList<A>();
items.add(new B());
process(items);

值得指出的是,使用此方法时,您将无法从流程内部将项目添加到myList中method@monkybonk05我没有意识到这一点,但我猜这个过程是为了处理已经存在的项目,而不是添加新的项目。:)你能解释一下为什么不可能做到这一点吗?我猜想这是因为数组是一个泛型类型。@西蒙和安德烈福斯伯格在你不知道列表中声明的一个实现的确切方法中,所以编译器不能确定你想放入列表中的内容是否被允许存在。@西蒙和安德烈福斯伯格回答你的问题,考虑下面的内容。如果有类型为B的列表,则不能添加类型为a的对象。例如,列表。添加(a)是一个编译错误,因为a不是B。因此,对于泛型列表类型方法参数,可以传递类型为a的列表或任何扩展(或在本例中实现)的对象因此,确保您不会将错误类型的对象添加到列表中的唯一方法是根本不允许您添加任何对象!这可能是一种选择,但这需要在我的一个非常专业化的对象中创建通用方法。我不喜欢混合抽象层次。
void process(List<? extends A> myList) {
}

List<A> items = new ArrayList<A>();
items.add(new B());
process(items);