在该类的方法体中实例化泛型类

时间:2013-03-07 14:46:35

标签: java list generics

我正在尝试在该类的方法中实例化泛型类,但是我遇到了编译时错误。希望有人能在这里提供一些见解:

//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

1 个答案:

答案 0 :(得分:2)

您应该使用ISelect的通用版本:

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

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