2016-03-02 41 views
1

我需要实现一个应用方法,使用binaryOperator来对两个双打执行一个数学过程,但无法找到如何执行。我的代码的目的是一次对两个数字应用apply-method,每一个都来自它的迭代器。找不到如何实现binaryOperator接口的应用方法java

我还没有被编程太久,所以我的代码可能有很多错误,但是这是多远我来,直到如今:

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

} 

回答

0

Iterator应该实施BinaryOperator。你的next()方法应该如下实现:

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

这应该可以覆盖它。

+0

谢谢,这帮了很多! – Camilla