簡體   English   中英

遍歷Java中的SortedSet

[英]Iterating through SortedSet in Java

我正在嘗試為存儲在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);
    }
 }

我當前的輸出是:

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

每個it.next()調用都會將迭代器轉發一步。 因此,在while循環的每次迭代中,您將失去一個間隔。 使用臨時變量保留以前的迭代器值。

對於像

Iterator<Double> it = val.iterator();
Object end=null;
if(it.hasNext()){
    end= it.next();
    //write out -infinity to previous.
}
while(it.hasNext()){
    Object start = end;
    end= it.next();
    //write out start - end interval
}
if(end != null){
// write out end to infinity 
} else {
   // there were no values in the array.
   // write out - infinity to infinity?
}

問題在以下循環中

while (it.hasNext()) {
    // Get element
    Object lowerBound = it.next();
    Object upperBound = it.next();
    arr.add(lowerBound+" - "+upperBound);
}

迭代器, it在單次迭代中增加兩倍it.next() ,最終生成您要獲取的數組。

解決方案如下:

Double lowerBound = neginf;
while (it.hasNext()) {
    // Get element
    Double upperBound = it.next();
    arr.add(lowerBound + " - "+ upperBound);
    lowerBound = upperBound;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM