2017-10-18 28 views
-1
public SortedArrayList<T> incrementItems(int increment) { 
for(T sh: this) { 
    Integer newValue = (Integer) sh + (Integer) increment; 
    this.set(this.indexOf(sh), (T) newValue); 
    } 
return this; 
} 
public SortedArrayList<T> incrementItems(int increment) { 
for(T sh: this) { 
    Integer newValue = (Integer) sh + (Integer) increment; 
    this.set(this.indexOf(sh), (T) newValue); 
    } 
return this; 
} 

這是我的方法,它只是遍歷列表中的每個元素並遞增值,它在80%的時間內運行良好。但是,如果1是「元素」,它會將其增加一倍(有時也是這樣)。遇到Eclipse中的「bug」或某些邏輯我不明白

我已經給下面的一些例子:

SortedArrayList<Integer> L1 = new SortedArrayList<Integer>(); 
    L1.addAll(Arrays.asList(1,3,6,1,6,6,7,8,11,11,14,15,20,20)); 
    System.out.println(L1.incrementItems(10)); 

輸出是: [21, 13, 16, 21, 16, 16, 17, 18, 11, 11, 24, 25, 30, 30]

SortedArrayList<Integer> L1 = new SortedArrayList<Integer>(); 
    L1.addAll(Arrays.asList(1,3,6,1,6,6,7,8,11,11,14,15,20,20)); 
    System.out.println(L1.incrementItems(9)); 

輸出爲:[10, 12, 24, 10, 15, 15, 16, 17, 29, 29, 23, 15, 20, 20]

SortedArrayList<Integer> L1 = new SortedArrayList<Integer>(); 
    L1.addAll(Arrays.asList(1,3,6,1,6,6,7,8,11,11,14,15,20,20)); 
    System.out.println(L1.incrementItems(4)); 

輸出是:[5, 19, 10, 5, 10, 10, 7, 12, 15, 11, 18, 15, 24, 24]

有些數字會觸發此事發生,有些則不會。所以我再次感謝任何反饋。

回答

4

這與Eclipse IDE無關。

您在List上調用indexOf,它將檢索第一個匹配的元素。

每一次。

docs

返回指定元素在此列表中第一次出現的索引[...]

所以,如果你是循環和1遇到兩次,indexOf將返回1的第一個位置,並且元素將遞增。

接下來會發生什麼是基於List中的其他項目:如果在迭代中稍後發現增量項目的匹配,則相同的項目將再次遞增,而後一個項目將保持不變。

作爲一個離題問題,您似乎在濫用泛型:您的SortedArrayList類接受任何類型的參數,但其incrementItems只假定值將爲Integer

注意

如果您使用的是Java 8,你可以利用map功能流的輕鬆投射所有List元素的增加值。

例如:

// this will generate a new `List` with incremented elements 
List<Integer> incremented = originalList 
    .stream() 
    .map(x -> Integer.sum(x, increment)) 
    .collect(Collectors.toList()); 

如果你被卡住前的Java 8個成語,你可以創建一個新的List的代碼,如:

List<Integer> incremented = new ArrayList<>(); 
for (Integer i: originalList) { 
    incremented.add(i + increment); 
} 
+1

好最後一點,也是 –

+2

是你確定它會得到兩次索引?我認爲它是相當於1遞增10到11,然後當它在列表indexOf(11)中達到11時將再次返回第一個索引,因爲該元素現在是11。 –

+0

我知道,該分配要求創建通用類,但在這種特定情況下,我們必須制定一個方法,除了列表中的整數外,其他方法基本上都沒有意義。因此,瘋狂的鑄造。 – AfroYak