我正在尝试为存储在 SortedSet 中的 double 值创建间隔。
下面是我的代码:
public class Trail {
public static void main(String[] args) {
SortedSet<Double> val = new TreeSet<Double>();
val.add(1.0);
val.add(2.0);
val.add(11.0);
val.add(12.0);
ArrayList<String> arr = new ArrayList<String>();
double posinf = Double.POSITIVE_INFINITY;
double neginf = Double.NEGATIVE_INFINITY;
arr.add(neginf+ " - " +val.first());
Iterator<Double> it = val.iterator();
while (it.hasNext()) {
// Get element
Object lowerBound = it.next();
Object upperBound = it.next();
arr.add(lowerBound+" - "+upperBound);
}
arr.add(val.last() + " - "+ posinf);
System.out.println("Range array: "+arr);
}
}
我当前的输出是:
Range array: [-Infinity - 1.0, 1.0 - 2.0, 11.0 - 12.0, 12.0 - Infinity]
我期望范围数组为:
[-Infinity - 1.0, 1.0 - 2.0, 2.0 - 11.0, 11.0 - 12.0, 12.0 - Infinity]
最佳答案
您在循环的每次迭代中消耗了两个元素(如果元素数量为奇数,则会引发异常)。您应该在每次迭代中只消耗一个:
Iterator<Double> it = val.iterator();
Double lowerBound = neginf;
while (it.hasNext()) {
// Get element
Double upperBound = it.next();
arr.add(lowerBound+" - "+upperBound);
lowerBound = upperBound;
}
arr.add(lowerBound + " - "+ posinf);
关于java - Java 中的 SortedSet 迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38097605/