英文:
Can't convert java.util.List to java.lang.Iterable of template interface
问题
我在使用一个实现接口的对象列表作为该接口的可迭代对象时遇到了问题。
我的类定义如下:
```java
class BaseObject implements AInterface<OtherObject> {...}
class Foo extends BaseObject{...}
interface BInterface{
void doSomething(AInterface<OtherObject> a);
void doSomethingToIterable(Iterable<AInterface<OtherObject>> a);
}
无法编译通过的代码如下:
private BInterface bInterface;
...
public void baa(List<Foo> list){
bInterface.doSomethingToIterable(list);//这行代码导致编译错误
...
}
我从Maven获取的编译错误信息如下:
不兼容的类型:java.util.List<my.package.Foo> 无法转换为java.lang.Iterable<my.other.package.AInterface<my.third.package.OtherObject>>
我可以对列表中的每个元素调用doSomething
。实际上,我可以通过内联实现doSomethingToIterable
来实现这一点。
在终端中运行java -version
会产生以下输出:
openjdk version "1.8.0_252"
OpenJDK Runtime Environment (build 1.8.0_252_b09)
OpenJDK 64-Bit Server VM (build 1.8.0_252_b09)
我理解的是,由于List
扩展了Collection
,而Collection
扩展了Iterable
,而Foo
扩展了实现了AInterface
的BaseObject
,所以这两种类型应该是兼容的。但似乎我的理解是错误的。
为什么会出现上述错误,如何修复它?
<details>
<summary>英文:</summary>
I'm having an issue using a list of objects implementing an interface as an iterable of that interface.
My class definitions are like this:
```java
class BaseObject implements AInterface<OtherObject> {...}
class Foo extends BaseObject{...}
interface BInterface{
void doSomething(AInterface<OtherObject> a);
void doSomethingToIterable(Iterable<AInterface<OtherObject>> a);
}
The code that won't compile is
private BInterface bInterface;
...
public void baa(List<Foo> list){
bInterface.doSomethingToIterable(list);//This is the line that gives a compilation error
...
}
The compilation error I'm getting from maven is
incompatible types: java.util.List<my.package.Foo> cannot be converted to java.lang.Iterable<my.other.package.AInterface<my.third.package.OtherObject>>
I can invoke doSomething
to each element in the List. In fact, I can do this by inlining the implementation of doSomethingToIterable
.
Running java -version
in terminal produces the output
openjdk version "1.8.0_252"
OpenJDK Runtime Environment (build 1.8.0_252_b09)
OpenJDK 64-Bit Server VM (build 1.8.0_252_b09)
My understanding is that since List
extends Collection
which extends Iterable
, and Foo
extends BaseObject
that implements AInterface
, these two types should be compatible. It seems my understanding is wrong.
Why am I getting the above error, and how can it be fixed?
答案1
得分: 3
List<Subclass>
不是 List<Superclass>
的实例。
尝试:
void doSomethingToIterable(Iterable<? extends AInterface<OtherObject>> a)
英文:
List<Subclass>
is not an instance of List<Superclass>
.
Try:
void doSomethingToIterable(Iterable<? extends AInterface<OtherObject>> a)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论