2.2 Lists Explained
Lists in Java are a fundamental part of the Java Collections Framework, providing a way to store and manipulate collections of objects. Understanding lists is crucial for managing ordered collections efficiently.
Key Concepts
1. List Interface
The List
interface extends the Collection
interface and represents an ordered collection of elements. It allows duplicate elements and provides methods to access elements by their index.
Example
Listlist = new ArrayList<>(); list.add("Apple"); list.add("Banana"); list.add("Cherry"); System.out.println(list.get(1)); // Output: Banana
2. ArrayList
An ArrayList
is a resizable array implementation of the List
interface. It provides fast random access and is suitable for scenarios where elements are frequently accessed by index.
Example
ListarrayList = new ArrayList<>(); arrayList.add(10); arrayList.add(20); arrayList.add(30); System.out.println(arrayList.get(2)); // Output: 30
3. LinkedList
A LinkedList
is a doubly-linked list implementation of the List
interface. It provides efficient insertion and deletion operations but slower random access compared to ArrayList
.
Example
ListlinkedList = new LinkedList<>(); linkedList.add("Dog"); linkedList.add("Cat"); linkedList.add("Bird"); System.out.println(linkedList.get(1)); // Output: Cat
4. List Operations
Lists support various operations such as adding elements, removing elements, accessing elements by index, and iterating through the list.
Example
Listfruits = new ArrayList<>(); fruits.add("Apple"); fruits.add("Banana"); fruits.add("Cherry"); fruits.remove("Banana"); System.out.println(fruits); // Output: [Apple, Cherry] for (String fruit : fruits) { System.out.println(fruit); }
Examples and Analogies
Think of a List
as a numbered list of items, similar to a shopping list where each item has a specific position. An ArrayList
is like a dynamic array that can grow or shrink as needed, while a LinkedList
is like a chain of items where each item is connected to the next and previous items.
By mastering lists, you can efficiently manage and manipulate ordered collections of data in your Java SE 11 applications.