Add Elements to Java String Array

There are several methods that can be used to add elements to a Java string array.

  1. Create a new array that is one element longer than the original array.
  2. Copy all elements from the original array to a new array.
  3. Place the element to be added at the last position of the new array.
  4. Assign the new array to the original array.
String[] originalArray = {"元素1", "元素2"};
String[] newArray = new String[originalArray.length + 1];
System.arraycopy(originalArray, 0, newArray, 0, originalArray.length);
newArray[newArray.length - 1] = "新元素";
originalArray = newArray;
  1. Create an ArrayList object with a type of String.
  2. Add elements to an ArrayList using the add() method.
  3. Convert ArrayList to a string array.
ArrayList<String> arrayList = new ArrayList<>();
arrayList.add("元素1");
arrayList.add("元素2");
arrayList.add("新元素");
String[] stringArray = arrayList.toArray(new String[0]);

In Java, once an array is created, its size is fixed and cannot be directly changed. Therefore, when adding elements, it is common to create a new array and copy elements from the original array to the new one. Alternatively, the ArrayList class can be used, as it can dynamically grow and shrink.

bannerAds