Java - Collection Framework Lists

Introduction

A list is an ordered collection of objects.

List interface represents a list in the Collections Framework.

A list can have duplicate elements. You can also store multiple null values in a list.

List interface inherits the Collection interface.

It adds methods to support access to elements of the List using indexes.

It allows you to add an element to the end of the List or at any position identified by an integer called the index.

The index of an element in a List is zero-based.

Types of List

The following are two of many implementation classes for the List interface:

  • ArrayList - backed up by an array
  • LinkedList - backed up by a linked list

An ArrayList performs better if you get and set the elements of the list frequently.

Accessing elements in an ArrayList is faster.

Adding or removing elements from ArrayList performs slower, unless done from the end.

LinkedList performs better for adding and removing elements from the middle of the list.

It is slower for accessing elements of the list, unless at the head of the list.

You can create and add some elements to a list as follows:

// Create a list of strings
List<String> nameList = new ArrayList<>();
nameList.add("XML");    // Adds XML at the index 0
nameList.add("Javascript"); // Adds Javascript at the index 1

You can also add elements to a List using positional indexes.

// Add an element at index 1
nameList.add(1, "Ruby");

The following code uses a List. It shows how to add, remove, and iterate over its elements using indexes.

Demo

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

public class Main {
  public static void main(String[] args) {
    // Create a List and add few elements
    List<String> list = new ArrayList<>();
    list.add("XML");
    list.add("Javascript");
    list.add("Json");
    list.add("Java");

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

    int count = list.size();
    System.out.println("Size of List: " + count);

    // Print each element with its index
    for (int i = 0; i < count; i++) {
      String element = list.get(i);
      System.out.println("Index=" + i + ", Element=" + element);
    }//from  w  w w.  j  ava 2s .c  om

    List<String> subList = list.subList(1, 3);
    System.out.println("Sub List 1 to 3(excluded): " + subList);
    // Remove "Json" from the list
    list.remove("Json"); // Same as list.remove(2);
    System.out.println("List (after removing Json): " + list);
  }
}

Result

Related Topics

Exercise