---
# System prepended metadata

title: Java List - Scaler Topics

---

---
title: Java List - Scaler Topics
description: This article by scaler topics defines the List in Java and also the various types of list classes with proper examples.
author: Aayush Saini
category: Java
---


:::section{.main}

`List` in Java provides the dynamic and an 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](https://www.scaler.com/topics/java/arraylist-in-java/), [LinkedList](https://www.scaler.com/topics/linked-list-in-java/), [vector](https://www.scaler.com/topics/java/vector-in-java/), `stack`, `copyonwriteArrayList`, and `Abstract list` implement the features of the list by implementing the `List` interface.
:::


:::section{.main}

## 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](https://scaler.com/topics/images/hierarchy-of-classes-java.webp)

### List Interface Declaration

```
public interface List<E> extends Collection<E>  
```
### Java List Methods


| Methods                                   | Description                                                                                                               |
| :-----------------------------------------: | :-----------------------------------------------------------------------------------------------------------------------------: |
| 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 `hashcode`        |This 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.

:::

:::section{.main}
## 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.

```java
// Creating a list of Object elements using ArrayList
List<Object> list = new ArrayList<>();
```    
    
However, to create a list for specific data types like int, float, etc., generics are utilized with wrapper classes:

```java
// Creating a list of Integer elements
List<Integer> list1 = new ArrayList<>();
List<Integer> list2 = new LinkedList<>();
List<Integer> list3 = new Stack<>();
List<Integer> list4 = new Vector<>();
```
    
* **Without Using the List Interface (Concrete Implementation):**
This approach uses classes implementing the List interface for list creation, allowing for distinct implementations.

```java
// Creating a list of Integer elements using ArrayList
ArrayList<Integer> list1 = new ArrayList<>();
LinkedList<Integer> list2 = new LinkedList<>();
Stack<Integer> list3 = new Stack<>();
Vector<Integer> list4 = new Vector<>();
```
    
Each list is instantiated with a specific class implementing the List interface.






:::

:::section{.main}
## Example of Java List 

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

```java
import java.util.*;

public class ListExample2 {
    public static void main(String[] args) {
        // Creating a List
        List<Integer> list = new ArrayList<>();

        // Adding elements to the List
        list.add(10);
        list.add(20);
        list.add(30);
        list.add(40);
        list.add(50);

        // Iterating over the List elements using for-each loop
        for (int number : list) {
            System.out.println(number);
        }
    }
}
```
**Output:**
```
10
20
30
40
50
```

### 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:

```java
import java.util.*;

public class ArrayToListExample {
    public static void main(String[] args) {
        // Defining an array of integers
        Integer[] array = {1, 2, 3, 4, 5};

        // Creating a list to store array elements
        List<Integer> list = new ArrayList<>();

        // Converting array elements to list
        for (Integer element : array) {
            list.add(element);
        }

        // Printing the elements of the list
        System.out.println("Array elements converted to list:");
        for (Integer element : list) {
            System.out.println(element);
        }
    }
}
```
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](https://www.scaler.com/topics/array-to-list-in-java/).


### Convert List to Array

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

```java
import java.util.*;

public class ListToArrayExample {
    public static void main(String[] args) {
        // Creating a List of integers
        List<Integer> list = new ArrayList<>();
        list.add(10);
        list.add(20);
        list.add(30);
        list.add(40);
        list.add(50);

        // Converting the List to an array of integers
        Integer[] array = list.toArray(new Integer[0]);

        // Printing the elements of the array
        System.out.println("Array elements:");
        for (Integer number : array) {
            System.out.println(number);
        }
    }
}
```
**Output:**

```
Array elements:
10
20
30
40
50
```
In this example, we first create a List of integers (List<Integer>), 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](https://www.scaler.com/topics/list-to-array-in-java/).
:::
:::section{.main}
## 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**
```java 
public static <T extends Comparable<? Super T>> void sort() (List<T> list)  
```
**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.**
```java 
List<Integer>lst = new ArrayList<Integer>();
lst.add(3);
lst.add(2);
lst.add(1);

//Printing the list
System.out.println(lst);

//Sort the elements of the list
Collections.sort(lst);

//Printing the sorted list
System.out.println(lst);
```
**Output:**
```plaintext
[3,2,1]
[1,2,3]
```
In the above snippet, we are sorting the list elements using the `collections.sort()` method.
    
:::

:::section{.main}
## 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.**
```java 
//Creating the list 
List<Integer>list = new ArrayList<Integer>();
list.add(1);
list.add(2);

//Printing the List
System.out.println(list);
```
**Output:**
```plaintext
[1,2]
```
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.
```java 
List<String>list = new ArrayList<String>();
list.add("Aayush");
list.add("saini");
list.add("Scaler");

//Printing the list
System.out.println(list);
list.set(1,"HelloScaler");

//Printing the list
System.out.println(list);
```
**Output:**
```plaintext
[Aayush, saini, Scaler]
[Aayush, HelloScaler, Scaler]
```
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.**
```java 
lst.add(1);
lst.add(10);
lst.add(2);
System.out.println(lst);

//Removing an element present at index 0
lst.remove(0);
System.out.println(lst);

//Removing the reference that has a value 10
lst.remove(new Integer(10));
System.out.println(lst);
```
**Output:**
```plaintext 
[1, 10, 2]
[10, 2]
[2]
```
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.
```java  
import java.util.ArrayList;
import java.util.List;

public class StringListExample {
    public static void main(String[] args) {
        // Create a list of strings
        List<String> words = new ArrayList<>();

        // Add some strings to the list
        words.add("apple");
        words.add("banana");
        words.add("orange");
        words.add("banana");
        int index = words.indexOf("banana");
        System.out.println(
                "The first occurrence of 'banana' is at index "
                        + index)
        int lastIndex = words.lastIndexOf("banana");
        System.out.println(
                "The last occurrence of 'banana' is at index "
                        + lastIndex);
    }
}
```
    
**Output:**

```plaintext
The first occurrence of 'banana' is at index 1
The last occurrence of 'banana' is at index 3
```

### 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.

```java
// Importing all utility classes
import java.util.*;

// Main class
class Main {
    // Main driver method
    public static void main(String args[]) {
        // Creating an object of List interface,
        // implemented by LinkedList class
        List<String> ll = new LinkedList<>();

        // Adding elements to the object of List interface
        ll.add("Hello");
        ll.add("World");
        // Accessing elements using get() method
        String first = ll.get(0);
        System.out.println(first);
    }
}
 ``` 
    
**Output:**

```plaintext
Hello
```
:::

:::section{.main}

## 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.
    
| Operation                                   | Time Complexity   |Space Complexity                                                                                                         |
| :-----------------------------------------: | :----------------|:--------------------------------------------------------------------------------------------------------------------------------------: |
| Adding Element |O(1)|O(1)|
| Removing Element| O(N)|O(1)|
|Replacing Element|O(N)|O(1)|
|Traversing/List Iteration|O(N)|O(1)|
     
:::
  
:::section{.main}
 
## 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.

```java
List<String> list = new ArrayList<>();
// Adding elements to the list...

for (int i = 0; i < list.size(); i++) {
    String element = list.get(i);
    // Process the element...
}
```
                                               
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.

```java
List<String> list = new ArrayList<>();
// Adding elements to the list...

for (String element : list) {
    // Process the element...
}
```

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.                                               
 :::
   
:::section{.main}
 
## 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 
public interface ListIterator<E> extends Iterator<E>      
```
### Java ListIterator Interface Methods

| Methods                                   | Description                                                                                                               |
| :-----------------------------------------: | :-----------------------------------------------------------------------------------------------------------------------------: |
| 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
    
    
```java
import java.util.*;

public class ListIteratorExample2 {
    public static void main(String args[]) {
        LinkedList<String> ll = new LinkedList<String>();

        ll.add("Alice");
        ll.add("Bob");
        ll.add("Charlie");
        ll.add(1, "David");

        ListIterator<String> itr = ll.listIterator();

        System.out.println("Traversing elements in forward direction");
        while (itr.hasNext()) {
            System.out.println("index: " + itr.nextIndex() + " value: " + itr.next());
        }

        System.out.println("Traversing elements in backward direction");
        while (itr.hasPrevious()) {
            System.out.println("index: " + itr.previousIndex() + " value: " + itr.previous());
        }
    }
}
```
**Output:**
    
```plaintext
Traversing elements in forward direction
index: 0 value: Alice
index: 1 value: David
index: 2 value: Bob
index: 3 value: Charlie
Traversing elements in backward direction
index: 3 value: Charlie
index: 2 value: Bob
index: 1 value: David
index: 0 value: Alice
```
    
:::

:::section{.summary}
## 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.
:::
