gpt4 book ai didi

java - 无法找到如何实现binaryOperator接口(interface)java的apply方法

转载 作者:太空宇宙 更新时间:2023-11-04 12:51:47 25 4
gpt4 key购买 nike

我需要使用binaryOperator 实现一个apply 方法来对两个 double 执行数学过程,但不知道如何操作。我的代码的目的是一次对两个数字应用 apply-method,每个数字都来自其各自的迭代器。

我编程的时间不长,所以我的代码可能有很多错误,但这就是我到目前为止所取得的进展:

package interfaces;

import java.util.Arrays;
import java.util.Iterator;
import java.util.function.BinaryOperator;

public class BinaryComputingIterator implements Iterator<Double>,
BinaryOperator<Double>{
private BinaryOperator<Double> operator;

private Iterator<Double> iterator1;
private Iterator<Double> iterator2;
private Double default1;
private Double default2;

BinaryComputingIterator(Iterator<Double> iterator1,
Iterator<Double> iterator2, BinaryOperator<Double> operator){
this.iterator1 = iterator1;
this.iterator2 = iterator2;
this.operator = operator;
}

BinaryComputingIterator(Iterator<Double> iterator1,
Iterator<Double> iterator2, Double default1, Double default2,
BinaryOperator<Double> operator){
this.iterator1 = iterator1;
this.iterator2 = iterator2;
this.operator = operator;
this.default1 = default1;
this.default2 = default2;
}

@Override
public boolean hasNext() {
if (iterator1.hasNext() && iterator2.hasNext()){
return true;
}
return false;
}

@Override
public Double next() {
if (this.hasNext()){
return this.next();
}
return null;
}

@Override

public Double apply(Double t, Double u) {
return this.operator.apply(t, u);
}

}

最佳答案

您的Iterator 不应实现BinaryOperator。您的 next() 方法应实现为

 public Double next() {
if (hasNext()) {
return operator.apply(iterator1.next(), iterator2.next());
} else {
throw new NoSuchElementException(); // specified in the Iterator contract
}
}

这应该几乎涵盖了它。

关于java - 无法找到如何实现binaryOperator接口(interface)java的apply方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35757534/

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