Java Collections: List
The Collections Framework provides ready-made data structures. List is an ordered collection that allows duplicate elements, with ArrayList and LinkedList as the most common implementations.
ArrayList is backed by a resizable array (fast random access), while LinkedList is backed by a doubly linked list (fast insertion/removal at the ends).
List<Type> list = new ArrayList<>();
list.add(value);ArrayList basics
ArrayList grows dynamically, unlike arrays. Common methods include add(), get(), remove(), size(), and contains().
Choosing List implementations
Use ArrayList for frequent random access and iteration; use LinkedList when you need frequent insertions/removals at the beginning or middle.
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Banana");
System.out.println(fruits);
System.out.println(fruits.get(0));
}
}[Apple, Banana]
Appleadd() appends elements, and get(0) retrieves the first element of the List.
Key points
- List allows duplicate elements and maintains insertion order.
- ArrayList is backed by a resizable array.
- LinkedList is efficient for insertions/removals at the ends.
- Common List methods: add, get, remove, size, contains.
