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.
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.
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.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 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.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.
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.
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.
A linked list (java.util.LinkedList) node in Java is a basic element of a linked list data structure, consisting of two main components:
- The data part that stores the element’s value, and
- a reference (or pointer) to the next node in the sequence, facilitating the link in the list.
Further Reading
- Add elements of a list to the same list in java
- Learn How To Convert An Array To An ArrayList In Java!
- See the Groovy Scripting Language category for other articles on this subject.
- See the Java Programming Language category for other articles on this subject.