java - 一次操作数组的所有元素

标签 java arrays

我假设答案是否定的,但我正在寻找一种方法来一次操作数组中的所有元素,而不是编写循环。例如,下面的代码创建两个数组,然后出错。显然,注释行不起作用,但我想避免为我需要应用的每个函数编写循环。

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/

相关文章:

arrays - 在具有重复元素的数组中查找最大值

java - Groovy 深拷贝 json 映射

java - (1.9) Minecraft纹理异常

javascript - 如何从 2 个数组中仅返回不重复的对象

java - 如何查看 int 数组中的元素是否为空?

c - 简单的C数组问题

javascript - 从 JSON 数据获取特定属性

java - 使用 Java 获取空指针异常

java - 我可以删除 xml 文件吗?安卓

java - 在 apache tomcat 7.0 上运行时出现 jersey 2.7 问题