I have string array (String[]
) and I need to remove the first item. How can I do that efficiently?
Most efficient way to remove an element from an array, then reduce the size of the array.
We can use the remove() method of ArrayList container in Java to remove the first element. ArrayList provides two overloaded remove() method: remove(int index) : Accept index of the object to be removed. We can pass the first element's index to the remove() method to delete the first element.
To remove the first element of an array in JavaScript, use array. shift() method. The shift() method changes the length of an array.
The size of arrays in Java cannot be changed. So, technically you cannot remove any elements from the array.
One way to simulate removing an element from the array is to create a new, smaller array, and then copy all of the elements from the original array into the new, smaller array.
String[] yourArray = Arrays.copyOfRange(oldArr, 1, oldArr.length);
However, I would not suggest the above method. You should really be using a List<String>
. Lists allow you to add and remove items from any index. That would look similar to the following:
List<String> list = new ArrayList<String>(); // or LinkedList<String>(); list.add("Stuff"); // add lots of stuff list.remove(0); // removes the first item
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With