List Interface in Java with Examples

In Java, the List interface is part of the Collection Framework and is used to represent an ordered collection of elements that can be accessed by their index. The elements in a List can be duplicated and null values are allowed. Some common implementations of the List interface are ArrayList, LinkedList, and Vector.

Here are some examples of how to use the List interface in Java:

Creating a List

List<String> fruits = new ArrayList<>(); // Creates an empty ArrayList of Strings
List<Integer> numbers = new LinkedList<>(); // Creates an empty LinkedList of Integers
List<Boolean> flags = new Vector<>(); // Creates an empty Vector of Booleans

Adding elements to a List

fruits.add("apple");
fruits.add("banana");
fruits.add("orange");​​

Accessing elements in a List

String fruit = fruits.get(0); // Retrieves the first element in the list ("apple")​​

Removing elements from a List

fruits.remove("banana");​​

Iterating over a List using a for-each loop

for (String fruit : fruits) {
    System.out.println(fruit);
}

Checking if a List contains a specific element

boolean containsOrange = fruits.contains("orange"); // Returns true​​

Getting the size of a List

int size = fruits.size(); // Returns the number of elements in the list (2)​​

Clearing a List

fruits.clear(); // Removes all elements from the list​​


Note that since the List interface extends the Collection interface, all methods defined in the Collection interface are also available in List.

In summary, the List interface provides a convenient way to work with ordered collections of elements in Java, and is a fundamental component of the Collection Framework.