在Java中迭代SortedSet

Unm*_*eni 2 java sortedset

我正在尝试为存储在SortedSet中的双值创建间隔.

以下是我的代码:

 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);
    }
 }
Run Code Online (Sandbox Code Playgroud)

我目前的输出是:

Range array: [-Infinity - 1.0, 1.0 - 2.0, 11.0 - 12.0, 12.0 - Infinity]
Run Code Online (Sandbox Code Playgroud)

我期望范围数组为:

[-Infinity - 1.0, 1.0 - 2.0, 2.0 - 11.0, 11.0 - 12.0, 12.0 - Infinity]
Run Code Online (Sandbox Code Playgroud)

Era*_*ran 6

在循环的每次迭代中消耗两个元素(如果元素的数量是奇数,则会抛出异常).您应该在每次迭代中只使用一个:

    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);
Run Code Online (Sandbox Code Playgroud)