In Java, the List interface is part of the java.util package and is a sub-interface of the Collection interface. It represents an ordered collection of elements where duplicates are allowed.
Lists can dynamically grow or shrink in size, and you can access elements based on their index (position in the list).
The List interface is commonly used when you need to maintain the order of elements and allow duplicates. There are various classes that implement the List interface, such as ArrayList, LinkedList, Vector, and Stack.
This tutorial will cover how to use the List interface with different implementations, providing multiple examples to demonstrate key features.
Table of Contents
1. Common Implementations of the List Interface
Here are the most commonly used classes that implement the List interface:
ArrayList: A resizable array that allows fast random access.
LinkedList: A doubly linked list that allows fast insertion and deletion.
Vector: Similar to ArrayList but is synchronized (thread-safe).
Stack: A subclass of Vector that follows the LIFO (Last-In-First-Out) principle.
2. Creating a List
You can create a List using different implementations. Below are examples of creating List objects using ArrayList and LinkedList:
Example: Creating a List
import java.util.ArrayList; import java.util.LinkedList; import java.util.List; public class ListCreationExample { public static void main(String[] args) { // Creating a List using ArrayList List arrayList = new ArrayList<>(); // Creating a List using LinkedList List linkedList = new LinkedList<>(); // Adding elements arrayList.add("Apple"); arrayList.add("Banana"); linkedList.add("Carrot"); linkedList.add("Date"); // Display the lists System.out.println("ArrayList: " + arrayList); System.out.println("LinkedList: " + linkedList); } }
Explanation:
We created two List objects: one using ArrayList and the other using LinkedList.
We added elements to both lists and displayed them.
Output:
ArrayList: [Apple, Banana] LinkedList: [Carrot, Date]
3. Adding Elements to a List
The List interface provides several methods to add elements:
add(E element): Adds an element to the list.
add(int index, E element): Adds an element at the specified position in the list.
Example: Adding Elements to a List
import java.util.ArrayList; import java.util.List; public class AddElementsExample { public static void main(String[] args) { // Creating an ArrayList List list = new ArrayList<>(); // Adding elements at the end of the list list.add("Java"); list.add("Python"); list.add("C++"); // Adding an element at a specific index list.add(1, "JavaScript"); // Displaying the list System.out.println("List after adding elements: " + list); } }
Explanation:
We added elements to the list using add() and inserted an element at a specific position using add(int index, E element).
Output:
List after adding elements: [Java, JavaScript, Python, C++]
4. Accessing Elements in a List
You can access elements in a List using the get(int index) method, which retrieves the element at the specified index.
Example: Accessing Elements
import java.util.ArrayList; import java.util.List; public class AccessElementsExample { public static void main(String[] args) { // Creating an ArrayList List list = new ArrayList<>(); // Adding elements list.add("Apple"); list.add("Banana"); list.add("Cherry"); // Accessing elements using get() String firstElement = list.get(0); String secondElement = list.get(1); // Displaying the elements System.out.println("First element: " + firstElement); System.out.println("Second element: " + secondElement); } }
Explanation:
We accessed elements at specific indexes using the get() method.
Output:
First element: Apple Second element: Banana
5. Modifying Elements in a List
You can modify elements in a List using the set(int index, E element) method, which replaces the element at the specified index.
Example: Modifying Elements
import java.util.ArrayList; import java.util.List; public class ModifyElementsExample { public static void main(String[] args) { // Creating an ArrayList List list = new ArrayList<>(); // Adding elements list.add("Red"); list.add("Green"); list.add("Blue"); // Modifying an element list.set(1, "Yellow"); // Displaying the modified list System.out.println("List after modification: " + list); } }
Explanation:
We replaced the element at index 1 with the new value “Yellow” using the set() method.
Output:
List after modification: [Red, Yellow, Blue]
6. Removing Elements from a List
You can remove elements from a List using:
remove(int index): Removes the element at the specified index.
remove(Object o): Removes the first occurrence of the specified element.
Example: Removing Elements
import java.util.ArrayList; import java.util.List; public class RemoveElementsExample { public static void main(String[] args) { // Creating an ArrayList List list = new ArrayList<>(); // Adding elements list.add("One"); list.add("Two"); list.add("Three"); list.add("Four"); // Removing an element by index list.remove(1); // Removes "Two" // Removing an element by object list.remove("Four"); // Displaying the modified list System.out.println("List after removals: " + list); } }
Explanation:
We removed elements by index using remove(int index) and by object using remove(Object o).
Output:
List after removals: [One, Three]
7. Iterating Over a List
There are several ways to iterate over the elements of a List:
Using a for-each loop.
Using a for loop with an index.
Using a ListIterator.
Using a Stream (Java 8+).
Example: Iterating Over a List
import java.util.ArrayList; import java.util.List; public class IterateListExample { public static void main(String[] args) { // Creating an ArrayList List list = new ArrayList<>(); list.add("Apple"); list.add("Banana"); list.add("Cherry"); // 1. Using for-each loop System.out.println("Using for-each loop:"); for (String fruit : list) { System.out.println(fruit); } // 2. Using for loop with index System.out.println("\nUsing for loop with index:"); for (int i = 0; i < list.size(); i++) { System.out.println(list.get(i)); } // 3. Using Java 8 Stream API System.out.println("\nUsing Stream API:"); list.stream().forEach(System.out::println); } }
Explanation:
We demonstrated three ways to iterate over the elements of the list: for-each loop, for loop with index, and the Java 8 Stream API.
Output:
Using for-each loop: Apple Banana Cherry Using for loop with index: Apple Banana Cherry Using Stream API: Apple Banana Cherry
8. Sorting a List
You can sort a List using the Collections.sort() method for natural ordering or by providing a comparator for custom sorting.
Example: Sorting a List
import java.util.ArrayList; import java.util.Collections; import java.util.List; public class SortListExample { public static void main(String[] args) { // Creating an ArrayList List list = new ArrayList<>(); list.add("Banana"); list.add("Apple"); list.add("Cherry"); // Sorting the list in natural order Collections.sort(list); // Displaying the sorted list System.out.println("Sorted list: " + list); } }
Explanation:
We used Collections.sort() to sort the list in natural alphabetical order.
Output:
Sorted list: [Apple, Banana, Cherry]
9. Checking if a List Contains an Element
You can check if a List contains a specific element using the contains(Object o) method.
Example: Checking for an Element
import java.util.ArrayList; import java.util.List; public class ContainsElementExample { public static void main(String[] args) { // Creating an ArrayList List list = new ArrayList<>(); list.add("Apple"); list.add("Banana"); list.add("Cherry"); // Check if the list contains "Banana" boolean containsBanana = list.contains("Banana"); System.out.println("Contains Banana? " + containsBanana); // Check if the list contains "Date" boolean containsDate = list.contains("Date"); System.out.println("Contains Date? " + containsDate); } }
Explanation:
We used contains() to check if the list contains specific elements.
Output:
Contains Banana? true Contains Date? false
10. Converting a List to an Array
You can convert a List to an array using the toArray() method.
Example: Converting List to Array
import java.util.ArrayList; import java.util.List; public class ListToArrayExample { public static void main(String[] args) { // Creating an ArrayList List list = new ArrayList<>(); list.add("Apple"); list.add("Banana"); list.add("Cherry"); // Convert list to array String[] array = list.toArray(new String[0]); // Display array elements System.out.println("Array elements:"); for (String fruit : array) { System.out.println(fruit); } } }
Explanation:
We converted the List to an array using toArray() and printed the elements of the array.
Output:
Array elements: Apple Banana Cherry
Conclusion
The List interface in Java is a powerful collection that allows you to store and manipulate ordered elements. It is versatile and commonly used in many applications. Key points covered:
Common implementations: ArrayList, LinkedList, Vector, and Stack.
Adding, accessing, modifying, and removing elements: Simple methods like add(), get(), set(), and remove().
Iterating over a list: Various ways like for-each, for loop with index, and streams.
Sorting and checking for elements: Collections.sort() and contains().
Converting lists to arrays: Using toArray().
By mastering these methods, you can effectively work with the List interface to store and manipulate data in Java.