Tutorial: Learn how to add elements to a List in Java! 🤔

In this guide, we’ll review how to add elements to a List in Java. As we’ll see, we do have several options available and these are appropriate when, for example, converting an array into an ArrayList — these choices generally involve performing the addition via the constructor or via various methods.

The solutions present in this article are compatible with Java 8 unless explicitly noted otherwise.

Since the java.util.List is an interface we need to pick an implementation for this tutorial and, in this case, we’ll explore how to add elements in linked list in Java.

How to add elements in a List in Java TOC

The LinkedList is dynamically sized thus making it an ideal choice when the number of elements is either unknown or changes frequently.

The LinkedList is especially efficient for insertions and deletions, as these operations only involve updating links between elements and not shifting elements as with what happens when the same operations take place when using an ArrayList.

LinkedList instances are thereby suitable for situations where frequent additions and removals are common.

There are trade-offs, however.

LinkedLists are less efficient for random access, as they require traversing the list to reach an element thus resulting in an O(n) time complexity compared to O(1) in an ArrayList.

Additionally, each LinkedList element requires extra memory for storing pointers, thereby leading to higher memory use.

Ultimately, the choice between a LinkedList and other data structures depends on the application’s specific requirements, balancing factors such as the types of operations performed with memory efficiency.

Finally, we’ll also take a look at some of the performance considerations when adding elements to a Java List.

Instructions regarding how to execute the example

In this section we’ll introduce an example application and how to execute this demonstration using the tio.run online interpreter.

Below I’ve included a short script that demonstrates how to add elements to an instance of java.util.LinkedList using the addAll method.

Note the red pointer on the top left indicates how to execute the program and the red pointer on the bottom of the image indicates where the output can be found.

Try It Online: How To Convert An Array To An ArrayList In Java
Try It Online: Add elements to a LinkedList!
Example regarding how to add elements in LinkedList in Java from TIO.run with pointers to the "run" icon and the output.
Example regarding how to add elements in LinkedList in Java from TIO.run.

How to add List elements in Java using the LinkedList constructor

In this example, we pass an instance of java.util.Collection as a parameter to the LinkedList constructor. This solution is appropriate for situations where we have an instance of Collection and the List has not been instantiated — if the list already exists then we’ll need to add elements using one of the instance methods available. Below I’ve included an example of the line of code where the LinkedList constructor is called and the reference to the uuidList is passed in.
				
					def exampleList = new LinkedList (uuidList) as java.util.List
				
			

I’ve included the full script and output below and, in this case, it took, on average, 9.7 seconds for this to run six times.

This example is written in Groovy and explains how to add elements to a list in Java via the LinkedList constructor.
Groovy script example explaining how to add elements to a List in Java via the LinkedList constructor.

In the next section, we’ll look at the add and addAll methods.

Use the add and addAll methods to insert elements into a java.util.LinkedList

We can use either the add and addAll methods to insert elements into a LinkedList in the Java Programming Language. The add method can be used when adding a single item to the LinkedList. The addAll method can be used when adding a Collection containing one or more elements to the LinkedList. The example screenshot below demonstrates the respective add and addAll method signatures.
Example add and addAll methods that can be used to add items to a linked list in Java.
Use the add and addAll methods to add elements in LinkedList in Java.

An index can be used in both the add and addAll methods to indicate where in the list the element(s) should be appended.

An example where we add an element to a linked list in Java at index two with a pointer to the add method and another pointer to the output.
How to add an element to a linked list in Java at index two.

The GitHub gist is available regarding how to insert elements into a List in Java on the right side of this page.

The add and addAll methods are defined in the java.util.List interface and hence all implementations of List will also have these methods.

The LinkedList addFirst and addLast convenience methods

When we need to insert elements into a LinkedList in Java we can use the addFirst and addLast convenience methods. The addFirst and addLast convenience methods offer significant benefits for efficient element insertion.
Java LinkedList element insertion using the addFirst and addLast convenience methods, which are only visible if we're using a LinkedList directly.
LinkedList element insertion using the addFirst and addLast convenience methods in Java.

The addFirst and addLast convenience methods allow for fast and straightforward additions at the beginning and end of the list, respectively, without the need for resizing or element shifting which would otherwise be required when using either simple arrays or instances of the Java ArrayList.

This aforementioned efficiency is due to the LinkedList structure, where such operations are performed in constant time (O(1)), involving only the modification of pointers.

The addFirst and addLast methods enhance code readability and simplify implementation, as they eliminate the need for index calculations.

The addFirst and addLast convenience methods are particularly advantageous in applications where the order of elements is important, such as with stacks and queues.

Utilizing the addFirst and addLast methods contributes to cleaner and more efficient code, optimizing operations in scenarios where frequent additions are made to either the beginning or end of the list.

In the next section, we’ll look at using the push method to append elements to a LinkedList in Java.

Insert elements into a List in Java using the push method

The push method is only available on classes that implement the Deque interface and this includes the LinkedList. It is for this reason that line #19 is of type java.util.LinkedList and not java.util.List. In this example, we can see that “Tomatoes” is pushed into the exampleList on line #23. When the push method is invoked, “Tomatoes” is inserted into the LinkedList at position zero and everything else is shifted rightward.
Java code with pointers to line #23 where the push method pushes an element onto the stack represented by this list, line #26 where we get the first element in the exampleList, and pointers to the output, where we can see that "Tomatoes" appears in position zero.
The LinkedList push method is used to add "Tomatoes" to the first position in the exampleList.

We can run this example in our browser using Try It Online, which offers interpreters for a growing list of practical and recreational programming languages, including the Java Programming Language.

The TIO icon on the right contains a link to the example shown here.

Tutorial Conclusion

This walk-through is a content experiment based on research from the StackOverflow post entitled How to add elements of a Java8 stream into an existing List along with some observations discovered while doing keyword research using SEMrush.

See also the article on Java autoboxing performance which can have a negative impact on performance when adding an array of primitive values to an instance of one of the Java Collections classes, such as a LinkedList.

If you’re looking to hire a Short-Term CTO then I might be able to help you — schedule an appointment with me today and we’ll discuss your requirements in more detail.

Frequently Asked Questions (FAQ)

This section includes frequently asked questions as it pertains to the Java Programming Language and various topics and components covered in this instructional.

What is a linked list in Java?

A <a href=”https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/LinkedList.html”>linked list in Java</a> is a data structure that consists of a sequence of elements, each contained in a node. Nodes are chained together using pointers, with each node pointing to the next node in the sequence. The use of pointers allows for efficient insertion and deletion of elements as it does not require shifting elements, which is required when relying on simple arrays.

What are linked lists good for in Java?

Linked lists in Java (java.util.LinkedList) are useful in scenarios where frequent insertion and deletion of elements is required, as these operations can be performed more efficiently than in arrays, because there’s no need to shift elements. Linked lists (java.util.LinkedList) are also useful when the size of the data structure needs to be dynamically allocated.

What is a linked list node in Java?

A linked list (java.util.LinkedList) node in Java is a basic element of a linked list data structure, consisting of two main components:

  1. The data part that stores the element’s value, and
  2. a reference (or pointer) to the next node in the sequence, facilitating the link in the list.
author avatar
ThosPFuller
I am a software engineer based in Northern Virginia (USA) and this website focuses on content engineering, content experiments, web development, search engine optimization and digital marketing ideas.

ThosPFuller

I am a software engineer based in Northern Virginia (USA) and this website focuses on content engineering, content experiments, web development, search engine optimization and digital marketing ideas.

Leave a Reply