How can Java add data at the end of an array?

In Java, you can add data to the end of an array using the following method:

  1. Create a new array with a length one greater than the original array.
  2. Copy all elements from the original array to a new array.
  3. Add new data to the last position of the new array.

Example code:

// 原数组
int[] originalArray = {1, 2, 3, 4, 5};

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

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

// 在新数组的最后一个位置添加新的数据
int newData = 6;
newArray[newArray.length - 1] = newData;

// 打印新数组
for (int i = 0; i < newArray.length; i++) {
    System.out.print(newArray[i] + " ");
}

Output result:

1 2 3 4 5 6
bannerAds