Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to remove the first element from an array?

Tags:

java

arrays

I have string array (String[]) and I need to remove the first item. How can I do that efficiently?

like image 740
NullVoxPopuli Avatar asked Sep 08 '10 01:09

NullVoxPopuli


People also ask

What is the most efficient way to remove an element from an array?

Most efficient way to remove an element from an array, then reduce the size of the array.

How do you remove the first element of an array in Java?

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.

How do you remove the first element of an object?

To remove the first element of an array in JavaScript, use array. shift() method. The shift() method changes the length of an array.


1 Answers

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 
like image 152
jjnguy Avatar answered Sep 20 '22 13:09

jjnguy