在该类的方法体内实例化一个泛型类
问题描述:
我试图在该类的一个方法内实例化一个泛型类,但有编译时错误。希望有人能提供一些见解这里:在该类的方法体内实例化一个泛型类
//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
答
您应该使用的ISelect
通用版:
public ILo<T> filter(ISelect<T> pred) {
return new ConsLo<T>(pred.select(this.first),
this.rest.filter(pred));
}
这样pred
将ISelect<T>
,而不是I选择 - 这是两种类型T#1
和T#2
编译器抱怨关于。
你的'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