Java List

Learn via video course
FREE
View all courses
Java Course - Mastering the Fundamentals
Java Course - Mastering the Fundamentals
by Tarun Luthra
1000
5
Start Learning
Java Course - Mastering the Fundamentals
Java Course - Mastering the Fundamentals
by Tarun Luthra
1000
5
Start Learning
Topics Covered

List in Java provides the dynamic and ordered collection of the user-defined or predefined elements. Lists in Java implement the List interface. Lists in Java can store null or duplicate elements. The list's internal working in Java is based on the indexing mechanism.

The classes such as ArrayList, LinkedList, vector, stack, copyonwriteArrayList, and Abstract list implement the features of the list by implementing the List interface.

List Interface in Java

The List interface contains the signature of many methods that help us to design many features in the class, like maintaining the order and insertion of the element at the particular index, etc. These classes use the abstract methods of the List interface to design the structure of its class.

Let's have a look at the hierarchy of these classes.

hierarchy of classes java

List Interface Declaration

Java List Methods

MethodsDescription
void add(int index,E)This method of List interface is used for inserting an element at the particular index of the list
boolean add(E e)Used to append the element at the end of the list and returns true if the element is successfully added.
void clear()It removes all the elements from the list.
boolean equals(Object o)This method is used to compare two objects.
int hashcodeThis method is used to get the hash value of an object.
E get(int index_value)This method is used to fetch an element that is present at the given index value in the list.
boolean isEmpty()It is used to determine whether the list is empty or not, if empty this method returns true, otherwise false.
int lastIndexOf(E e)This method is used to get the last index value of the given object. If the object is not present in the list, this method returns -1.
boolean contains(Object E)This method is used to check whether the list contains specialized objects in the list or not; if present, this method returns true; otherwise, it returns false.
int indexOf(Object E)This method is used to fetch the first index position of the given object in the list, if the object is not present, This method returns -1.
List remove(int index)This method is used to remove the element or object present at the given index position. An exception will occur if we provide an invalid index value.
boolean remove(Object E)This method removes an object from the list and returns a boolean value.
List set(int index, Object)This method is used to set an object at the given index position in the list.
int size()This method is used to determine the size of the List. The return type of this method is int.
Spliterator<E> spliterator()Create a spliterator over the elements in a list.
boolean addAll(Collection<? extends E> c)Used for appending the particular collection at the end of the existing list.
List.toArray()This method returns the array containing all list elements in an ordered way.

These are some methods of the List interface, and many classes implement these methods to perform their respective operations.

How to Create the List?

In Java, various classes implement the List interface, such as ArrayList, Vector, Stack, LinkedList, etc., providing different implementations for creating lists.

There are two primary methods to create a list in Java:

  • Using the List Interface (Programming to Interface): This approach leverages the List interface, enabling flexibility and adherence to interface contracts.

However, to create a list for specific data types like int, float, etc., generics are utilized with wrapper classes:

  • Without Using the List Interface (Concrete Implementation): This approach uses classes implementing the List interface for list creation, allowing for distinct implementations.

Each list is instantiated with a specific class implementing the List interface.

Example of Java List

Below is a simple example demonstrating how to create a list of numbers and then print them out.

Output:

Convert Array to List

Converting an array to a list in Java involves traversing the array and adding each element to a list using the list.add() method. Below is a straightforward example demonstrating this process:

In this example, we start with an array of integers. Then, we create an empty list to store the array elements. By iterating over the array using a for-each loop, we add each element to the list using the list.add() method. Finally, we print the list elements to verify the conversion from array to list.

To learn more about it, visit here.

Convert List to Array

To convert a List to an array, we will use the list.toArray() method in Java. let's see the below example to understand better.

Output:

In this example, we first create a List of integers (List), add some integers, and then convert it to an array of integers using the list.toArray(new Integer[0]) method. Finally, we iterate over the array and print its elements.

To learn more about it in detail, visit here.

How to Sort List in Java?

The collections.sort() method of the collection interface is used to sort the list in Java such as ArrayList, vector, Stack, LinkedList.

Syntax

Parameters: This method takes only one parameter, i.e. the list that needs to be sorted.

Return type: This method doesn't return anything.

Let's understand this method using an example.

Output:

In the above snippet, we are sorting the list elements using the collections.sort() method.

Operations in a Java List Interface

Let's understand some operations of the list interface methods.

1. Adding Elements to List Using add() method

The List interface contains an abstract method, i.e. add() method, implemented by multiple classes and used for adding the elements in the list.

Let's understand adding elements to the list using the add() method.

Output:

In the above snippet, we are adding the elements in the list using the add() method of the ArrayList class.

2. Updating Elements in the List class using set() method

The set() method of the List interface is used for updating elements in the list class. We have already discussed this method's syntax and return type in the above section. Please have a look at the table to understand better.

Output:

In the above snippet, we are updating the String at index 1 with the "HelloScaler" String in the list.

3. Removing Elements Using remove() Method

The remove() method of the List interface is used to remove elements from the list. This method takes the index of the element that needs to be removed or an object of the element.

Let's understand this method using an example.

Output:

In the above snippet, we remove the elements from the given list using the indexing method and the reference method.

4. Searching Elements Using indexOf() Method

The List interface offers convenient methods to facilitate this operation, including indexOf() and lastIndexOf().

The indexOf() method identifies the index of the initial occurrence of a specified element in the list. Conversely, the lastIndexOf() method retrieves the index of the final occurrence of the specified element.

Output:

5. Accessing Element Using get() method

To retrieve an element from a list, you can utilize the get() method. It returns the element located at the specified index within the list.

Output:

Complexity of List Interface in Java

The table below summarizes the time and space complexities associated with joint operations performed on lists implemented through the List interface in Java.

OperationTime ComplexitySpace Complexity
Adding ElementO(1)O(1)
Removing ElementO(N)O(1)
Replacing ElementO(N)O(1)
Traversing/List IterationO(N)O(1)

Iterating over List Interface in Java

There are different ways to iterate through the List. We have discussed the most famous wats by using the basic for loop with the get method, and another is an advanced for loop

  • Basic for Loop with get() Method:

This method involves using a traditional for loop in conjunction with the get() method to access elements by their index.

Here, the loop iterates over the list indices, and list.get(i) fetch the element at each index for processing.

  • Enhanced for Loop (for-each Loop):

The enhanced for loop provides a concise syntax for iterating through the elements of a collection, including lists.

This loop iterates through each element in the list directly without needing to manage indices explicitly. It offers cleaner code and is particularly useful when only accessing elements sequentially.

Java ListIterator Interface

The ListIterator interface in Java enables bidirectional traversal of elements within a List, allowing forward and backwards navigation through the collection. It offers methods for iterating over the elements with more control than a regular Iterator.

ListIterator Interface Declaration

Java ListIterator Interface Methods

MethodsDescription
void add(E e)This method adds the specified element to the end of the list.
E next()This method retrieves the next element in the list and moves the cursor forward to the subsequent position.
void set(E e)This method updates the last element accessed by either the next() or previous() methods with the specified element.
void remove()This method removes the element at the current position of the iterator, which was returned by the next() or previous() methods.
int nextIndex()This method retrieves the index of the element that would be returned by the next call to the iterator's next() method.
boolean hasPrevious()This method checks whether the list iterator has additional elements remaining while moving through the list in reverse order.
boolean hasNext()This method evaluates to true if the list iterator can advance further while moving through the list in the forward direction.
E previous()This method retrieves the previous element in the list and shifts the cursor position backwards.
E previousIndex()This method provides the index of the element that will be accessed if you call the previous() method next.

Example of Java ListIterator Interface

Output:

Conclusion

  • Java lists offer a dynamic and ordered collection of elements, accommodating user-defined and predefined data types.
  • Serving as the universal interface for list operations, the List interface unifies functionality across various list implementations.
  • While ArrayList excels in rapid element retrieval due to its array-based structure, LinkedList shines in efficient insertion and deletion operations within the list.