List
The List interface is a part of the Java Collections Framework and represents an ordered collection that can contain duplicate elements. Unlike Set
, a List
maintains the order in which elements are inserted and allows for random access to its elements via an index.
Key Implementations of List
ArrayList:
- An
ArrayList
is a resizable array implementation of theList
interface. It provides fast random access to elements but can be slower when adding or removing elements at arbitrary positions (except at the end).
List<String> names = new ArrayList<>(); names.add("Alice"); names.add("Bob");
- An
2. **LinkedList**:
* A `LinkedList` is a doubly linked list implementation of the `List` interface. It offers better performance than `ArrayList` when adding or removing elements from the beginning or middle of the list.
```java
List<String> names = new LinkedList<>();
names.add("Alice");
names.add("Bob");
Vector:
- A
Vector
is similar to anArrayList
, but it is synchronized, making it thread-safe. However, its usage has been largely replaced byArrayList
.
List<String> names = new Vector<>(); names.add("Alice"); names.add("Bob");
- A
Important Methods in List
add(E e):
- Adds the specified element to the list.
list.add("Alice");
get(int index):
- Retrieves the element at the specified position in the list.
String name = list.get(0); // Access first element
remove(int index):
- Removes the element at the specified position.
list.remove(0); // Removes the first element
set(int index, E element):
- Replaces the element at the specified position with the specified element.
list.set(0, "New Name");
contains(Object o):
- Checks if the list contains the specified element.
boolean containsAlice = list.contains("Alice");
size():
- Returns the number of elements in the list.
int size = list.size();
Example: Using List
import java.util.*;
public class ListExample {
public static void main(String[] args) {
// Creating a List
List<String> names = new ArrayList<>();
// Adding elements
names.add("Alice");
names.add("Bob");
names.add("Charlie");
// Retrieving an element
System.out.println("First element: " + names.get(0)); // Output: Alice
// Removing an element
names.remove("Bob");
// Checking size
System.out.println("Size of list: " + names.size());
// Iterating through the list
for (String name : names) {
System.out.println(name);
}
}
}