Collections Framework - The List Interface

In this chapter, we will learn about List interface of the Java Collections framework with an example.

List Interface Overview

  • List interface is a child interface of the Collection interface.
  • If we want to represent a group of individual objects where duplicates are allowed and insertion order preserved. Then we should go for List.
  • We can preserve insertion order and we can differentiate duplicate objects by using Index hence index will play a very important role in List.
  • The user of this interface has precise control over where in the list each element is inserted.
  • A list may contain multiple null elements.
  • List interface can contain duplicate elements. 
List interface implementations classes:

List Interface Example

Here is a simple List interface example using the ArrayList implementation class. This example demonstrates that List allows to store duplicate elements, null values, and maintains the insertion order:

package com.java.collections.interfaces;

import java.util.ArrayList;
import java.util.List;

public class ListDemo {
    public static void main(String[] args) {
        List < String > list = new ArrayList < > ();
        // List allows you to add duplicate elements
        list.add("element1");
        list.add("element1");
        list.add("element2");
        list.add("element2");
        System.out.println(list);

        // List allows you to have ‘null’ elements.
        list.add(null);
        list.add(null);
        System.out.println(list);

        // insertion order
        list.add("element1"); // 0
        list.add("element2"); // 1
        list.add("element4"); // 2
        list.add("element3"); // 3
        list.add("element5"); // 4

        System.out.println(list);

        // access elements from list

        System.out.println(list.get(0));
        System.out.println(list.get(4));

    }
}
Output
[element1, element1, element2, element2]
[element1, element1, element2, element2, null, null]
[element1, element1, element2, element2, null, null, element1, element2, element4, element3, element5]
element1
null

The List Interface Class Diagram

From the above diagram, the List interface extends the Collection interface. So, All methods of Collection interface are inherited to the List interface. 

List Interface Methods

This class diagram shows a list of APIs/Methods that the List interface provides.

List Interface Common Implementation

List interface implementations classes:

What's next?

In this chapter, we have learned all about the List interface, it's methods, and usage with examples.

Comments