What are Lists?
In Java, a List is an ordered collection (also known as a sequence) that allows duplicate elements. It is part of the Java Collections Framework and is defined in the java.util package.
Key Characteristics of Lists:
- Ordered collection (elements have a specific order)
- Allow duplicate elements
- Elements can be accessed by their index
- Dynamic size (can grow or shrink as needed)
The List interface in Java has several implementations, including ArrayList and LinkedList, which we'll explore in detail.
import java.util.List;
import java.util.ArrayList;
public class ListExample {
public static void main(String[] args) {
// Creating a List of Strings
List fruits = new ArrayList<>();
// Adding elements to the List
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Orange");
// Printing the List
System.out.println("Fruits: " + fruits);
// Accessing elements by index
System.out.println("First fruit: " + fruits.get(0));
// Checking if an element exists
System.out.println("Contains 'Banana': " + fruits.contains("Banana"));
// Getting the size of the List
System.out.println("Number of fruits: " + fruits.size());
}
}
This example demonstrates creating a List, adding elements, accessing elements, and performing basic operations. Try running this code in the compiler below and experiment with different List operations.