gpt4 book ai didi

java - 在该类的方法体内实例化泛型类

转载 作者:行者123 更新时间:2023-11-30 04:28:25 25 4
gpt4 key购买 nike

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

//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));
}

我提供了方法的接口(interface)定义,然后是 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> ,而不是 ISelect - 这是两种类型 T#1T#2编译器正在提示。

关于java - 在该类的方法体内实例化泛型类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15274165/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com