1

我正在尝试在该类的方法中实例化一个泛型类,但出现编译时错误。希望有人可以在这里提供一些见解:

//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 类的定义,然后是我正在处理的方法声明。我不明白如何实例化这个类,同时保持通用性,以便使用任何类型和谓词谓词。这是编译器错误:

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
4

1 回答 1

2

您应该使用以下通用版本ISelect

public ILo<T> filter(ISelect<T> pred) {
    return new ConsLo<T>(pred.select(this.first),
        this.rest.filter(pred));
}

这种方式pred将是,而不是 ISelect - 这是编译器抱怨ISelect<T>的两种类型。T#1T#2

于 2013-03-07T14:53:44.760 回答