Remove an Item from 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 remove the item from the ArrayList and convert the ArrayList back to an array.
The following code shows how this might be done. Please also refer to the code in the posts linked above.
public static String[] RemoveItemFromArray(String[] array, String item) { ArrayList list = CreateStringList(array); list.remove(item); return ConvertArrayListToArray(list); } public static String[] RemoveItemFromArray(String[] array, int index) { ArrayList list = CreateStringList(array); list.remove(index); return ConvertToStringArray(list); }
Nice clean code, but what if I wanted to remove a row from a multi-dimenensional String array
You should be able to do it with a multidimensional array. You’d just treat each element as an array. Have you tried and it didn’t work? If so, can you post a (simple) code snippet?
and what if i want to remove indexes from a non-primitive type? (yes i know String isn’t techniqually a primitive data type)
Say i have an array of type “TetrisBox”, and suddenly 10 of these indexes or elements, i don’t want anymore, i want to get rid of them (i’m sure you can see the reason for this). how would i do that? because i obviously can’t pass them as a string?
You’d do it about the same way. First you’d need to convert the array to an ArrayList. Then you’d need to get the index (indices) of the objects. You can do this using the indexOf method on ArrayList. However, make sure you override the equals method in the TetrixBox class. See this post http://code.hammerpig.com/find-an-object-in-an-arraylist-with-java.html. Then remove the objects based on the indices.
Hopefully I’m understanding your question correctly. Please let me know if this helped.