List Interface

📋 What is the List Interface?

The List interface in Java is a subinterface of Collection that represents an ordered collection of elements. It allows:

  • Duplicate elements
  • Access via index
  • Maintains insertion order

🧠 Package: java.util.List


✅ Key Features:

  • Indexed access: Elements can be accessed by position (e.g., list.get(0)).
  • Duplicates allowed
  • Order preserved (elements stay in the order they are added)

🔧 Common Implementations:

Implementation Characteristics
ArrayList Fast for read, slow for insert/delete
LinkedList Fast for insert/delete, slower for read
Vector Synchronized (thread-safe, legacy)
Stack LIFO (Last In First Out) structure

🧰 Common Methods in List:

Method Description
add(E e) Adds an element at the end
add(int index, E) Adds an element at specified index
get(int index) Returns the element at given index
remove(int index) Removes element at specified index
set(int index, E) Updates element at index
indexOf(Object o) Returns first index of element (or -1)
size() Returns number of elements

🔍 Example:

import java.util.*;

public class ListExample {
    public static void main(String[] args) {
        List<String> cities = new ArrayList<>();

        cities.add("Delhi");
        cities.add("Mumbai");
        cities.add("Chennai");
        cities.add("Delhi"); // Duplicates allowed

        cities.set(1, "Bangalore"); // Replace Mumbai with Bangalore

        for (String city : cities) {
            System.out.println(city);
        }

        System.out.println("City at index 0: " + cities.get(0));
    }
}


🧠 Summary:

Feature List Interface
Order Maintains insertion order
Duplicates Allowed
Access By index (zero-based)
Use cases To-do lists, shopping carts, etc.
Back to blog

Leave a comment

Please note, comments need to be approved before they are published.