Add Elements to Java String Array
There are several methods that can be used to add elements to a Java string array.
- Create a new array that is one element longer than the original array.
- Copy all elements from the original array to a new array.
- Place the element to be added at the last position of the new array.
- 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;
- Create an ArrayList object with a type of String.
- Add elements to an ArrayList using the add() method.
- 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.