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(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); }
this code does not work because CreateStringList(array) is not a valid method
Make sure you read the code on the linked articles. http://code.hammerpig.com/convert-an-array-to-an-arraylist-in-java.html
i can’t understand why we use position and array.length ???
Umar, you are correct that we don’t need to specify array.length in the first example. I have edited the post and removed this. We also could get away with not specifying a position in the second example. However, in the example, I made it possible to add it at a specific position just to demonstrate that you’re not limited to adding to the end.