我的问题与我之前在这个名为FilteringFlatApplyFunction的类中创建的FlatApply类有关。我似乎无法正确实现apply,因为静态类继续告诉我它需要是抽象的并且@Override不按照它应该的方式工作。我正在寻找的最终目标是使用继承从FlatApply类借用大部分功能并实现过滤器类的方法。我尝试了许多不同的东西,但仍然无法得到它,谓词" pred"检查给定的谓词是否为真,如果是,则表示返回元素,我认为会实现FlatApply,我现在已经得到了这个错误。感谢
错误:
FilteringFlatApplyFunction不是抽象的,并且不会覆盖FlatApplyFunction中的抽象方法apply(T) 其中T是一个类型变量: T扩展在FilteringFlatApplyFunction类中声明的Object
package iterators;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import iterators.Apply;
// Iterator that uses a Predicate to filter out elements from the input
public class Filter<T> extends FlatApply<T,T> {
public Filter(Predicate<T> p, Iterator<T> input) {
super(new FilteringFlatApplyFunction<T>(p),input);
}
// uses a Predicate to decide whether the input element is output or not
private static class FilteringFlatApplyFunction<T> implements FlatApplyFunction<T,T> {
private final Predicate pred;
public FilteringFlatApplyFunction(Predicate<T> p) {
this.pred = p;
}
@Override
public T apply(Iterator T) {
T result = null;
if((!T.hasNext())) throw new IllegalStateException();
if (pred.check(T.next()) == true){
result = (T) T.next();
}
else{
return (T) T;
}
}
这是FlatApply
package iterators;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
public class FlatApply<InT,OutT> implements Iterator<OutT> {
private final Iterator<InT> input;
private final FlatApplyFunction<InT,OutT> f;
private final Queue<OutT> q;
public FlatApply(FlatApplyFunction<InT,OutT> f, Iterator<InT> input) {
this.input = input;
this.f = f;
this.q = new LinkedList<OutT>();
}
@Override
public boolean hasNext() {
if (!q.isEmpty()) {
return true;
}
else {
while(q.isEmpty() && input.hasNext()) {
List<OutT> result = f.apply(input.next());
q.addAll(result);
}
if(q.isEmpty()) return false;
else return true;
}
}
@Override
public OutT next() {
if((!hasNext())) throw new IllegalStateException();
return q.poll();
}
}
这是FlatApplyFunction
package iterators;
import java.util.List;
public interface FlatApplyFunction<InT, OutT> {
public List<OutT> apply(InT x);
}
这是申请类
package iterators;
import java.util.Iterator;
public class Apply<InT,OutT> implements Iterator<OutT> {
// The function that will be applied to each input element to make an output element
private final ApplyFunction<InT,OutT> f;
// The Iterator that this Apply object will get its input from
private final Iterator<InT> input;
public Apply(ApplyFunction<InT, OutT> f, Iterator<InT> input) {
this.input = input;
this.f = f;
}
@Override
public boolean hasNext() {
return input.hasNext();
}
@Override
public OutT next() {
if((!hasNext())) throw new IllegalStateException();
OutT result = f.apply(input.next());
return result;
}
}
答案 0 :(得分:1)
FlatApplyFunction
界面说明了这一点:
public List<OutT> apply(InT x);
但该接口的FilteringFlatApplyFunction
实现说明了这一点:
public T apply(Iterator T) {
界面需要返回List
,您只需返回T
即可。此外,该参数必须为T
,但您将其设为Iterator
。
进行那些匹配,这个编译器错误应该消失。