我試圖在該類的一個方法內實例化一個泛型類,但有編譯時錯誤。希望有人能提供一些見解這裏:在該類的方法體內實例化一個泛型類
//returns a new ILo<T> with all items in this list that satisfy
//the given predicate
public ILo<T> filter(ISelect<T> pred);
// Represents a nonempty list of items of type T
class ConsLo<T> implements ILo<T>{
T first;
ILo<T> rest;
//returns a new ILo<T> with all items in this list that satisfy
//the given predicat
public ILo<T> filter(ISelect pred) {
return new ConsLo<T>(pred.select(this.first),
this.rest.filter(pred));
}
我提供方法的接口定義,其次是ConsLo類的定義,然後由我處理方法聲明。我不明白我如何在保留泛型的同時實例化這個類,以便處理任何類型和謂詞pred。以下是編譯器錯誤:
ILo.java:95: error: method select in interface ISelect<T#3> cannot be applied to given types;
return new ConsLo<T>(pred.select(this.first),
^
required: T#1
found: T#2
reason: actual argument T#2 cannot be converted to T#1 by method invocation conversion
where T#1,T#2,T#3 are type-variables:
T#1 extends Object declared in method <T#1>filter(ISelect<T#1>)
T#2 extends Object declared in class ConsLo
T#3 extends Object declared in interface ISelect
你的'filter'實現不需要通用的'ISelect',這可能是你的問題。 – Jeffrey 2013-03-07 14:49:49
大概應該是'public ILo filter(ISelect pred){'注** ** **新增。 –
OldCurmudgeon
2013-03-07 14:51:12
我試過這兩個想法,也沒有編譯 – 2013-03-07 14:52:51