温馨提示×

java怎么在数组中插一个数

小亿
89
2024-04-12 09:35:08
栏目: 编程语言

要在数组中插入一个数,可以先创建一个新的数组,然后将原数组中的元素复制到新数组中,同时在要插入的位置插入新的数值。以下是一个示例代码:

public class Main {
    public static void main(String[] args) {
        int[] originalArray = {1, 2, 3, 4, 5};
        int insertValue = 10;
        int insertIndex = 2; // 要在第2个位置插入数值10

        int[] newArray = new int[originalArray.length + 1];

        for (int i = 0, j = 0; i < newArray.length; i++) {
            if (i == insertIndex) {
                newArray[i] = insertValue;
            } else {
                newArray[i] = originalArray[j];
                j++;
            }
        }

        // 打印新数组
        for (int num : newArray) {
            System.out.print(num + " ");
        }
    }
}

在上面的示例代码中,我们在数组中的第2个位置插入了数值10,最终打印出了新的数组。

0