The List interface is a fundamental part of Java's Collections Framework. It represents an ordered collection of elements, allowing duplicate values and providing precise control over where elements are inserted in the list.
Java provides several implementations of the List interface:
Here's a simple example of creating and using a List:
import java.util.ArrayList;
import java.util.List;
public class ListExample {
public static void main(String[] args) {
List<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Cherry");
System.out.println(fruits); // Output: [Apple, Banana, Cherry]
System.out.println("Size: " + fruits.size()); // Output: Size: 3
System.out.println("Contains Banana? " + fruits.contains("Banana")); // Output: true
}
}
Method | Description |
---|---|
add(E element) | Adds an element to the end of the list |
add(int index, E element) | Inserts an element at the specified position |
get(int index) | Returns the element at the specified position |
remove(int index) | Removes the element at the specified position |
set(int index, E element) | Replaces the element at the specified position |
size() | Returns the number of elements in the list |
clear() | Removes all elements from the list |
There are several ways to iterate through a List in Java:
List<String> colors = Arrays.asList("Red", "Green", "Blue");
// Using enhanced for loop
for (String color : colors) {
System.out.println(color);
}
// Using iterator
Iterator<String> iterator = colors.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
// Using forEach method (Java 8+)
colors.forEach(System.out::println);
While both List and Set are collection interfaces, they have key differences:
The List interface is a versatile tool in Java programming. It provides a flexible way to store and manipulate ordered collections of elements, making it essential for many data processing tasks.