当我尝试运行时,我增强的for循环返回IndexOutOfBoundsException:
public static ArrayList<Double> multipliser(ArrayList<Double> listen, int multi) {
for(double elementer : listen) {
listen.set((int) elementer, listen.get((int) elementer * multi));
}
return listen;
Run Code Online (Sandbox Code Playgroud)
它与完美的旧循环完美配合:
for(int i = 0; i < listen.size(); i++) {
listen.set(i, listen.get(i) * multi);
}
return listen;
Run Code Online (Sandbox Code Playgroud)
我错过了什么?
listen.get((int) elementer * multi)
Run Code Online (Sandbox Code Playgroud)
是不一样的
listen.get(i)*multi
Run Code Online (Sandbox Code Playgroud)
同样在set
.
但是,通过一个常量就地(在Java 8+中)将列表中的所有内容相乘的更简单方法是:
listen.replaceAll(x -> x * multi);
Run Code Online (Sandbox Code Playgroud)
Java 8之前最简单的方法是使用ListIterator
:
for (ListIterator<Double> it = listen.listIterator(); it.hasNext();) {
it.set(it.next() * multi);
}
Run Code Online (Sandbox Code Playgroud)
(请注意,这大致是Collection.replaceAll
Java 8+中默认的外观实现方式).
归档时间: |
|
查看次数: |
82 次 |
最近记录: |