Java List Interface

Java is a highly flexible and extensively utilized programming language that presents a strong array of data structures for efficiently managing groups of objects. Among the essential data structures within Java is the List interface, which furnishes a sequentially arranged assortment of elements with adaptable sizing. This interface, integrated into the Java Collections Framework, furnishes a versatile and orderly approach for managing element collections. In the following segment, we will delve into the characteristics, realizations, and recommended methodologies linked with Java Lists.

In Java, the List interface allows for the organized storage of elements. It offers methods based on index positions for adding, modifying, removing, and locating elements. Lists can include duplicate elements and can store null values as well.

The List interface is located within the java.util package and extends the Collection interface. It serves as a creator of the ListIterator interface. With ListIterator, we have the capability to traverse the list both forwards and backwards. The concrete classes that implement the List interface include ArrayList, LinkedList, Stack, and Vector. Among these, ArrayList and LinkedList are extensively utilized in Java development. It is worth noting that the Vector class has been marked as deprecated starting from Java 5.

List Interface Declaration

Example

public interface List<E> extends Collection<E>

Java List Class Methods

Method Description
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 List interface is implemented by the ArrayList and LinkedList classes. Below are examples demonstrating how to instantiate a List:

Example

//Creating a List of type String using ArrayList

List<String> list=new ArrayList<String>();



//Creating a List of type Integer using ArrayList

List<Integer> list=new ArrayList<Integer>();



//Creating a List of type Book using ArrayList

List<Book> list=new ArrayList<Book>();



//Creating a List of type String using LinkedList

List<String> list=new LinkedList<String>();

Put simply, it is possible to generate a List of any kind by utilizing the ArrayList<T> and LinkedList<T> classes to define the type, with T representing the type.

Common List Operations

Below are several fundamental actions that can be executed on Java Lists.

  1. Inserting Elements:
  2. Example
    
    list.add("Java");
    
    list.add(1, "JavaScript");
    
  3. Removing Elements:
  4. Example
    
    list.remove("Java");
    
    list.remove(0);
    
  5. Accessing Elements:
  6. Example
    
    String firstElement = list.get(0);
    
    int index = list.indexOf("JavaScript");
    
  7. Iterate Over List:
  8. Example
    
    for (String element : list) 
    
    {
    
        System.out.println(element);
    
    }
    

    Java List Example

Let's examine a basic illustration of a List utilizing the ArrayList class as its implementation.

Example

Example

import java.util.*;

public class Main{

public static void main(String args[]){

 //Creating a List

 List<String> list=new ArrayList<String>();

 //Adding elements in the List

 list.add("Mango");

 list.add("Apple");

 list.add("Banana");

 list.add("Grapes");

 //Iterating the List element using for-each loop

 for(String fruit:list)

  System.out.println(fruit);



}

}

Output:

Output

Mango

Apple

Banana

Grapes

How to convert Array to List

A typical task in Java programming involves converting an array into a list. One way to achieve this is by iterating over the array and sequentially adding each element to the list using the List.add method. This method is commonly employed for this purpose. Additionally, there are alternative approaches that can be utilized, such as:

Method 1: Using Arrays.asList

Method 2: Using ArrayList Constructor

Example

Example

import java.util.*;

public class Main{

public static void main(String args[]){

//Creating Array

String[] array={"Java","Python","PHP","C++"};

System.out.println("Printing Array: "+Arrays.toString(array));

//Converting Array to List

List<String> list=new ArrayList<String>();

for(String lang:array){

list.add(lang);

}

System.out.println("Printing List: "+list);



}

}

Output:

Output

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

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

How to convert List to Array

To transform a List into an Array, we can utilize the List.toArray method. Below is a straightforward illustration demonstrating how to convert elements from a list into an array.

Example

Example

import java.util.*;

public class Main{

public static void main(String args[]){

 List<String> fruitList = new ArrayList<>();  

 fruitList.add("Mango");  

 fruitList.add("Banana");  

 fruitList.add("Apple");  

 fruitList.add("Strawberry");  

 //Converting ArrayList to Array

 String[] array = fruitList.toArray(new String[fruitList.size()]);  

 System.out.println("Printing Array: "+Arrays.toString(array));

 System.out.println("Printing List: "+fruitList);

}

}

Output:

Output

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

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

Get and Set Element in List

The get function retrieves the item located at the specified index, while the set function modifies or substitutes the item.

Example

Example

import java.util.*;

public class Main{

 public static void main(String args[]){

 //Creating a List

 List<String> list=new ArrayList<String>();

 //Adding elements in the List

 list.add("Mango");

 list.add("Apple");

 list.add("Banana");

 list.add("Grapes");

 //accessing the element  

 System.out.println("Returning element: "+list.get(1));//it will return the 2nd element, because index starts from 0

 //changing the element

 list.set(1,"Dates");

 //Iterating the List element using for-each loop

 for(String fruit:list)

  System.out.println(fruit);



 }

}

Output:

Output

Returning element: Apple

Mango

Dates

Banana

Grapes

How to Sort a List?

To arrange a list in Java, you can utilize either the Collections.sort function or the List.sort function that was added in Java 8. Below are demonstrations for both methods:

Example

Example

import java.util.*;

class Main{

 public static void main(String args[]){

  //Creating a list of fruits

  List<String> list1=new ArrayList<String>();

  list1.add("Mango");

  list1.add("Apple");

  list1.add("Banana");

  list1.add("Grapes");

  //Sorting the list

  Collections.sort(list1);

   //Traversing list through the for-each loop

  for(String fruit:list1)

    System.out.println(fruit);

    

 System.out.println("Sorting numbers...");

  //Creating a list of numbers

  List<Integer> list2=new ArrayList<Integer>();

  list2.add(21);

  list2.add(11);

  list2.add(51);

  list2.add(1);

  //Sorting the list

  Collections.sort(list2);

   //Traversing list through the for-each loop

  for(Integer number:list2)

    System.out.println(number);

 }

 

}

Output:

Output

Apple

Banana

Grapes

Mango

Sorting numbers...

1

11

21

51

Java ListIterator Interface

The ListIterator Interface enables the traversal of elements in both backward and forward directions.

ListIterator Interface declaration

Example

public interface ListIterator<E> extends Iterator<E>

Methods of Java ListIterator Interface

Method Description
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

Example

Example

import java.util.*;

public class Main{

public static void main(String args[]){

List<String> al=new ArrayList<String>();  

		al.add("Amit");  

		al.add("Vijay");  

		al.add("Kumar");  

		al.add(1,"Sachin");  

		ListIterator<String> itr=al.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:

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 consider an illustration of a list where we are including various books.

Example

Example

import java.util.*;

class Book {

int id;

String name,author,publisher;

int quantity;

public Book(int id, String name, String author, String publisher, int quantity) {

	this.id = id;

	this.name = name;

	this.author = author;

	this.publisher = publisher;

	this.quantity = quantity;

}

}

public class Main {

public static void main(String[] args) {

	//Creating list of Books

	List<Book> list=new ArrayList<Book>();

	//Creating Books

	Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);

	Book b2=new Book(102,"Data Communications and Networking","Forouzan","Mc Graw Hill",4);

	Book b3=new Book(103,"Operating System","Galvin","Wiley",6);

	//Adding Books to list

	list.add(b1);

	list.add(b2);

	list.add(b3);

	//Traversing list

	for(Book b:list){

	System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.quantity);

	}

}

}

Output:

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?
  • It extends the List interface.
  • It allows bidirectional traversal of elements in a list.
  • It is implemented by the ArrayList class only.
  • It is used to synchronize access to a list.

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

  1. What is the difference between ArrayList and LinkedList in Java?
  • ArrayList is synchronized while LinkedList is not.
  • ArrayList stores elements in a contiguous memory block while LinkedList uses a doubly-linked list.
  • ArrayList allows constant-time positional access while LinkedList does not.
  • ArrayList is a resizable array implementation of the List interface while LinkedList is a doubly-linked list implementation.

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.

  1. What is the time complexity of the add(int index, E element) operation in ArrayList and LinkedList respectively?
  • O(1) and O(n)
  • O(n) and O(1)
  • O(log n) and O(log n)
  • O(n) and O(n)

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.

  1. What is the purpose of the replaceAll(UnaryOperator <E> operator) method in the List interface?
  • It replaces all occurrences of a specific element in the list.
  • It replaces all elements in the list with a new specified element.
  • It applies the specified unary operator to each element in the list, replacing each element with the result of the operator.
  • It removes all occurrences of a specific element from the list.

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.

  1. Which method is used to obtain a portion of a list between two specified indices?
  • slice(int fromIndex, int toIndex)
  • portion(int fromIndex, int toIndex)
  • subList(int fromIndex, int toIndex)
  • range(int fromIndex, int toIndex)

The method subList(int fromIndex, int toIndex) in the List interface is utilized to retrieve a segment of a list starting from the designated fromIndex (inclusive) up to the toIndex (exclusive).

Input Required

This code uses input(). Please provide values below: