Add an Item to an Array in Java
If you haven’t read this post that talks about the differences between arrays and ArrayLists, that would be a good first step. Typically you would use an ArrayList rather than an array if you want to be able to add and remove objects. However, if you would rather (or are required to) use arrays, this can be a workaround.
The first step would be to convert the array to an ArrayList temporarily. Then you add the item to the ArrayList and convert the ArrayList back to an array.
The following code shows to append an item to the end of an array. Please also refer to the code linked to above.
public static String[] AppendItemToArray(String[] array, String newValue) { ArrayList<String> list = CreateStringList(array); list.add(array.length, newValue); return ConvertToStringArray(list); }
The following code shows to how to add an item at a specific position in the array.
public static String[] AddItemToArray(String[] array, String newValue, int position) { ArrayList<String> list = CreateStringList(array); list.add(position, newValue); return ConvertToStringArray(list); }