Java List

Java, a versatile and widely-used programming language, offers a robust set of data structures to handle collections of objects efficiently. One of the fundamental data structures in Java is the List interface that provides an ordered collection of elements with dynamic sizing. It is a part of Java Collections Framework, provides a versatile and ordered way to handle collections of elements. In this section, we will explore the features, implementations, and best practices associated with Java Lists.

List in Java provides the facility to maintain the ordered collection. It contains the index-based methods to insert, update, delete and search the elements. It can have the duplicate elements also. We can also store the null elements in the list.

The List interface is found in the java.util package and inherits the Collection interface. It is a factory of ListIterator interface. Through the ListIterator, we can iterate the list in forward and backward directions. The implementation classes of List interface are ArrayList, LinkedList, Stack, and Vector. The ArrayList and LinkedList are widely used in Java programming. The Vector class is deprecated since Java 5.

List Interface Declaration

Java List Class Methods

MethodDescription
void add(int index, E element)It is used to insert the specified element at the specified position in a list.
boolean add(E e)It is used to append the specified element at the end of a list.
boolean addAll(Collection<? extends E> c)It is used to append all of the elements in the specified collection to the end of a list.
boolean addAll(int index, Collection<? extends E> c)It is used to append all the elements in the specified collection, starting at the specified position of the list.
void clear()It is used to remove all of the elements from this list.
boolean equals(Object o)It is used to compare the specified object with the elements of a list.
int hashcode()It is used to return the hash code value for a list.
E get(int index)It is used to fetch the element from the particular position of the list.
boolean isEmpty()It returns true if the list is empty, otherwise false.
int lastIndexOf(Object o)It is used to return the index in this list of the last occurrence of the specified element, or -1 if the list does not contain this element.
Object[] toArray()It is used to return an array containing all of the elements in this list in the correct order.
<T> T[] toArray(T[] a)It is used to return an array containing all of the elements in this list in the correct order.
boolean contains(Object o)It returns true if the list contains the specified element
boolean containsAll(Collection<?> c)It returns true if the list contains all the specified element
int indexOf(Object o)It is used to return the index in this list of the first occurrence of the specified element, or -1 if the List does not contain this element.
E remove(int index)It is used to remove the element present at the specified position in the list. 
boolean remove(Object o)It is used to remove the first occurrence of the specified element. 
boolean removeAll(Collection<?> c)It is used to remove all the elements from the list. 
void replaceAll(UnaryOperator<E> operator)It is used to replace all the elements from the list with the specified element. 
void retainAll(Collection<?> c)It is used to retain all the elements in the list that are present in the specified collection. 
E set(int index, E element)It is used to replace the specified element in the list, present at the specified position. 
void sort(Comparator<? super E> c)It is used to sort the elements of the list on the basis of specified comparator. 
Spliterator<E> spliterator()It is used to create spliterator over the elements in a list. 
List<E> subList(int fromIndex, int toIndex)It is used to fetch all the elements lies within the given range. 
int size()It is used to return the number of elements present in the list. 

How to create List?

The ArrayList and LinkedList classes provide the implementation of List interface. Let's see the examples to create the List:

In short, we can create the List of any type. The ArrayList<T> and LinkedList<T> classes are used to specify the type. Here, T denotes the type.

Common List Operations

Here are some essential operations we can perform on Java Lists.

1. Adding Elements:

2. Removing Elements:

3. Accessing Elements:

4. Iterate Over List:

Java List Example

Let's see a simple example of List where we are using the ArrayList class as the implementation.

ListExample1.java

Output:

Mango
Apple
Banana
Grapes

How to convert Array to List

Converting an array to a list in Java is a common operation. We can convert the Array to List by traversing the array and adding the element in list one by one using the List.add() method. It is a common approach that we use. Beside this there are some other approaches we can use as follows:

Method 1: Using Arrays.asList()

Method 2: Using ArrayList Constructor

ArrayToListExample.java

Output:

Printing Array: [Java, Python, PHP, C++]
Printing List: [Java, Python, PHP, C++]

How to convert List to Array

We can convert the List to Array by calling the List.toArray() method. Let's see a simple example to convert list elements into array.

ListToArrayExample.java

Output:

Printing Array: [Mango, Banana, Apple, Strawberry]
Printing List: [Mango, Banana, Apple, Strawberry]

Get and Set Element in List

The get() method returns the element at the given index, whereas the set() method changes or replaces the element.

ListExample2.java

Output:

Returning element: Apple
Mango
Dates
Banana
Grapes

How to Sort a List?

Sorting a list in Java can be done using the Collections.sort() method or by using the List.sort() method introduced in Java 8. Here are examples for both approaches:

SortArrayList.java

Output:

Apple
Banana
Grapes
Mango
Sorting numbers...
1
11
21
51

Java ListIterator Interface

ListIterator Interface is used to traverse the element in a backward and forward direction.

ListIterator Interface declaration

Methods of Java ListIterator Interface

MethodDescription
void add(E e)The method inserts the specified element into the list.
boolean hasNext()The method returns true if the list iterator has more elements while traversing the list in the forward direction.
E next()The method returns the next element in the list and advances the cursor position.
int nextIndex()The method returns the index of the element that would be returned by a subsequent call to next()
boolean hasPrevious()The method returns true if this list iterator has more elements while traversing the list in the reverse direction.
E previous()The method returns the previous element in the list and moves the cursor position backward.
E previousIndex()The method returns the index of the element that would be returned by a subsequent call to previous().
void remove()The method removes the last element from the list that was returned by next() or previous() methods
void set(E e)The method replaces the last element returned by next() or previous() methods with the specified element.

Example of ListIterator Interface

ListIteratorExample1.java

Output:

Traversing elements in forward direction
index:0 value:Amit
index:1 value:Sachin
index:2 value:Vijay
index:3 value:Kumar
Traversing elements in backward direction
index:3 value:Kumar
index:2 value:Vijay
index:1 value:Sachin
index:0 value:Amit

Example of List: Book

Let's see an example of List where we are adding the Books.

ListExample5.java

Output:

101 Let us C Yashwant Kanetkar BPB 8
102 Data Communications and Networking Forouzan Mc Graw Hill 4
103 Operating System Galvin Wiley 6

Java List MCQ

1. Which of the following statements about the ListIterator interface in Java is true?

  1. It extends the List interface.
  2. It allows bidirectional traversal of elements in a list.
  3. It is implemented by the ArrayList class only.
  4. It is used to synchronize access to a list.

Answer: b)

Explanation: The ListIterator interface provides methods for traversing a list in both forward and backward directions, allowing bidirectional access to list elements.


2. What is the difference between ArrayList and LinkedList in Java?

  1. ArrayList is synchronized while LinkedList is not.
  2. ArrayList stores elements in a contiguous memory block while LinkedList uses a doubly-linked list.
  3. ArrayList allows constant-time positional access while LinkedList does not.
  4. ArrayList is a resizable array implementation of the List interface while LinkedList is a doubly-linked list implementation.

Answer: d)

Explanation: ArrayList internally uses a dynamic array to store elements, while LinkedList uses a doubly-linked list. This fundamental difference affects their performance characteristics and suitability for different scenarios.


3. What is the time complexity of the add(int index, E element) operation in ArrayList and LinkedList respectively?

  1. O(1) and O(n)
  2. O(n) and O(1)
  3. O(log n) and O(log n)
  4. O(n) and O(n)

Answer: b)

Explanation: In ArrayList, inserting an element at a specific index requires shifting subsequent elements, resulting in a time complexity of O(n). In LinkedList, inserting an element at a specific index can be done in constant time (O(1)) by adjusting the pointers, as it involves traversing to the desired position.


4. What is the purpose of the replaceAll(UnaryOperator <E> operator) method in the List interface?

  1. It replaces all occurrences of a specific element in the list.
  2. It replaces all elements in the list with a new specified element.
  3. It applies the specified unary operator to each element in the list, replacing each element with the result of the operator.
  4. It removes all occurrences of a specific element from the list.

Answer: c)

Explanation: The replaceAll() method in the List interface applies the specified unary operator to each element in the list, replacing each element with the result of the operator.


5. Which method is used to obtain a portion of a list between two specified indices?

  1. slice(int fromIndex, int toIndex)
  2. portion(int fromIndex, int toIndex)
  3. subList(int fromIndex, int toIndex)
  4. range(int fromIndex, int toIndex)

Answer: c)

Explanation: The subList(int fromIndex, int toIndex) method in the List interface is used to obtain a portion of a list between the specified fromIndex (inclusive) and toIndex (exclusive).