Course contentsShow
← Java
Lesson 969 of 2,87023. Collections Framework OverviewFree lesson

List Interface: Ordered Collections with Duplicates

Explore List as an ordered collection allowing duplicates, with positional access and index-based operations.

List Interface: Ordered Collections with Duplicates

What you'll learn: How the List interface provides ordered collections that allow duplicate elements and support index-based access.


What Makes List Special?

The List interface extends Collection and adds a crucial characteristic: order matters. Unlike sets, a List remembers the sequence in which elements were added and allows you to access them by their position (index). It also permits duplicate values.

Think of a List like a numbered playlist: each song has a position (0, 1, 2...), you can have the same song multiple times, and the order defines how they'll play.

Key Characteristics

Ordered Collection: Elements maintain insertion order. The first element you add stays at index 0, the second at index 1, and so on.

Duplicates Allowed: You can add the same element multiple times:

List<String> names = new ArrayList<>();
names.add("Alice");
names.add("Bob");
names.add("Alice");  // Perfectly valid—Alice appears twice

Positional Access: Retrieve elements by their numeric index:

String first = names.get(0);   // "Alice"
String third = names.get(2);   // "Alice" again

Index-Based Operations: Beyond retrieval, you can insert at specific positions, replace elements, or find the index of an item:

names.set(1, "Charlie");       // Replace Bob with Charlie
names.add(1, "Diana");         // Insert Diana at position 1
int index = names.indexOf("Alice");  // Returns 0 (first occurrence)

Why Use List?

When order matters and you need quick access to elements by position, List is your go-to interface. It's perfect for maintaining sequences, rankings, or any collection where you care about "first," "second," and "last."

Key Takeaway: The List interface provides ordered collections with positional access and allows duplicates, making it ideal when element sequence matters and you need index-based operations like get(int), set(int, E), and indexOf(Object).