遇到Eclipse中的“bug”或某些逻辑我不明白
问题描述:
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]
有些数字会触发此事发生,有些则不会。所以我再次感谢任何反馈。
答
这与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递增10到11,然后当它在列表indexOf(11)中达到11时将再次返回第一个索引,因为该元素现在是11。 –
我知道,该分配要求创建通用类,但在这种特定情况下,我们必须制定一个方法,除了列表中的整数外,其他方法基本上都没有意义。因此,疯狂的铸造。 – AfroYak