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.