java - Java 中的 SortedSet 迭代

标签 java sortedset

我正在尝试为存储在 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/

相关文章:

java - 如何检测玩家之前是否玩过游戏

java - 框架布局在底部导航栏后面?

set - 在 Redis 中使用 WATCH 实现 ZMOVE

redis - 如何与redis的排序集相交?

java - 如何迭代 SortedSet 以修改其中的项目

java - 如何跳过await driver().manage().timeOut()

java - 如何使用光学字符识别确定图像中的数字是否相同或不同?

java - 在 JScrollPane 内的 JPanel 内包装 JLabel

java - 在 Java 中,有什么比将 SortedSet 转换为 Vector 更有效的替代方法呢?

list - redis 以原子方式切换值