List in Java
List is a collection interface for an ordered sequence of elements. Every element has an index, starting at zero. A list can contain equal values more than once, and its order does not mean the values are automatically sorted.
Why Do We Need This?
A playlist may contain the same song twice and keep songs in the order selected by the listener. A list fits this kind of sequence because both position and repetition can matter.
Main Ideas
| Concept | What it means |
|---|---|
| add(value) | Adds a value when supported |
| get(index) | Reads the value at a position |
| set(index, value) | Replaces a value when supported |
| remove(index) | Removes the value at a position when supported |
| ArrayList and LinkedList | Two implementations with different storage and operation costs |
Simple Working Example
Run this program on its own. All required imports and classes are included.
import java.util.ArrayList;
import java.util.List;
public class HelloWorld {
public static void main(String[] args) {
List<String> lessons = new ArrayList<>();
lessons.add("Arrays");
lessons.add("Strings");
lessons.add("Arrays");
System.out.println(lessons);
System.out.println("Second lesson: " + lessons.get(1));
System.out.println("Size: " + lessons.size());
}
}Output
[Arrays, Strings, Arrays]
Second lesson: Strings
Size: 3ArrayList keeps the insertion sequence here, including the repeated Arrays value. get(1) reads the second element. Not every List supports adding or removing elements; some lists are unmodifiable.
Topics in This Section
Easy Way to Remember
Choose a list when position and sequence matter. The next lessons cover ArrayList, LinkedList, and the older Vector and Stack classes.
See you in next page....??