Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE

1. Overview

In this tutorial, we’ll look at how to remove the first element of an array.

In addition, we’ll also see how using data structures from the Java Collections Framework makes things even easier.

2. Using Arrays.copyOfRange()

First of all, removing an element of an array isn’t technically possible in Java. To quote the official docs:

“An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed.”

This means as long as we’re working with an array directly, all we can do is create a new array of smaller size, which then doesn’t contain the first element.

Luckily the JDK provides a convenient static helper function we can use, called Arrays.copyOfRange():

String[] stringArray = {"foo", "bar", "baz"};
String[] modifiedArray = Arrays.copyOfRange(stringArray, 1, stringArray.length);

Note that this operation has a cost of O(n) since it will create a new array every time.

Of course, this is a cumbersome way to remove an element from the array and if you are doing such operations regularly, it might be more sensible to use the Java Collections Framework instead.

3. Using a List Implementation

In order to keep roughly the same semantics of the data structure (an ordered sequence of elements that are accessible by index), it makes sense to use an implementation of the List interface.

The two most common implementations are ArrayList and LinkedList.

Suppose we have the following Lists:

List<String> arrayList = new ArrayList<>();
// populate the ArrayList

List<String> linkedList = new LinkedList<>();
// populate the LinkedList

Since both classes implement the same interface, the example code to remove the first element looks the same:

arrayList.remove(0);
linkedList.remove(0);

In the case of ArrayList, the cost of removing is O(n), while LinkedList has a cost of O(1).

Now, this doesn’t mean we should use a LinkedList everywhere as the default since the cost for retrieving an object is the other way around. The cost of calling get(i) is O(1) in the case of ArrayList and O(n) in the case of LinkedList.

4. Conclusion

We’ve seen how to remove the first element of an array in Java. In addition, we’ve looked at how to achieve the same result using the Java Collections Framework.

You can find the example code over on GitHub.

Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE
res – REST with Spring (eBook) (everywhere)
Comments are closed on this article!