我假设答案是否定的,但我正在寻找一种方法来一次操作数组中的所有元素,而不是编写循环。例如,下面的代码创建两个数组,然后出错。显然,注释行不起作用,但我想避免为我需要应用的每个函数编写循环。
package com.company;
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] foo = new int[10];
int[] bar = new int[10];
for (int i = 0; i < 10; i++){
bar[i]=i;
}
foo += bar; // want to add elements of these arrays pairwise. this fails.
bar += 1; // want to add 1 to each element of the array. this also fails.
System.out.println(Arrays.toString(foo));
}
}
最佳答案
对 java 数组的单个元素集的任何操作都需要循环,无论是显式(for 循环)还是隐式(map 函数)。您当然可以编写一个对象来展示您在 foo 和 bar 行中看到的行为,以隐藏循环,但它仍然存在。 (当然,您无法使用运算符重载并使 + 运算符成为等式的一部分 - 它必须是方法调用)
关于java - 一次操作数组的所有元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27031464/