2013-03-07 108 views
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类的定义,然后由我处理方法声明。我不明白我如何在保留泛型的同时实例化这个类,以便处理任何类型和谓词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 
+0

你的'filter'实现不需要通用的'ISelect',这可能是你的问题。 – Jeffrey 2013-03-07 14:49:49

+0

大概应该是'public ILo filter(ISelect pred){'注** ** **新增。 – OldCurmudgeon 2013-03-07 14:51:12

+0

我试过这两个想法,也没有编译 – 2013-03-07 14:52:51

回答

2

您应该使用的ISelect通用版:

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

这样predISelect<T>,而不是I选择 - 这是两种类型T#1T#2编译器抱怨关于。

+1

pedortry的注意事项:在Java中它被称为泛型。 – Jeffrey 2013-03-07 14:55:07

+0

我通常会使用它,但很多人开始称它为*模板* - 我想这就是初学者更容易理解它的方式,这就是我在这里使用它的原因。否则你是对的,我正在更新。 – gaborsch 2013-03-07 14:58:15

+0

是的,这是一个需要的改变,但我有一个方法的底层问题,我选择的是布尔类型而不是T类型。感谢您的输入,我会在接受它时接受 – 2013-03-07 14:59:14