[英]Java: Type mismatch with iterator of generic class
我想為一個通用的類創建一個Iterator,它工作正常。 我以為迭代器會嘗試使用泛型類的TypeParameter進行迭代,但是顯然並非如此,因為Eclipse告訴我期望有一個Object。
如果有人知道我做錯了什么,我會很高興。
public class GenericClass<T extends OtherClass> implements Comparable, Iterable
{
private ArrayList<T> list = new ArrayList<T>();
[...]
@Override
public Iterator<T> iterator()
{
Iterator<T> iter = list .iterator();
return iter;
}
[...]
}
public class Main
{
public static void main(String[] args)
{
GenericClass<InstanceOfOtherClass> gen = new GenericClass<InstanceOfOtherClass>("Aius");
for(InstanceOfOtherClass listElement : gen) // This is the problem line; gen is underlined and listElement is expected to be an Object
{
System.out.println(listElement.getName());
}
}
}
implements Comparable, Iterable
您需要指定基本接口的通用參數。
否則,您將非通用地實現Iterable
,並且type參數將變為Object
。
如果你想使你的類通用像GenericClass<T extends OtherClass>
那么你應該實現Comparable<T>
和Iterable<T>
的T
在兩種情況下是一樣T
的宣布GenericClass
。
這樣,當您執行通用類型實例化時,如下所示:
GenericClass<InstanceOfOtherClass> //...
結果將是它正在實現Comparable<InstanceOfOtherClass>
和Iterable<InstanceOfOtherClass>
,這使方法簽名匹配。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.