Adding Elements to Java Arrays

In Java, the length of an array is fixed and cannot be dynamically adjusted once created. However, you can achieve the effect of adding elements to an array by creating a new array and copying the elements from the original array into the new array. The specific steps are as follows:

  1. Create a new array with a length one greater than the original array to store the result after adding elements.
  2. Copy the elements from the original array into the new array one by one.
  3. Put the elements to be added at the end of the new array.
  4. Assign the new array to the original array to complete the operation of adding elements.

Here is a sample code:

// 定义一个空数组
int[] arr = new int[0];

// 添加元素
int element = 10;

// 创建一个新的数组,长度比原数组长1
int[] newArr = new int[arr.length + 1];

// 将原数组中的元素复制到新数组中
for (int i = 0; i < arr.length; i++) {
    newArr[i] = arr[i];
}

// 将要添加的元素放入新数组的最后一个位置
newArr[newArr.length - 1] = element;

// 将新数组赋值给原数组
arr = newArr;

In this way, the original empty array arr has added an element. Please note that since the array length is fixed, a new array needs to be created every time an element is added, resulting in lower efficiency. If there is a need to frequently add elements, it is recommended to use dynamic array classes such as ArrayList instead.

bannerAds