A List is one of the most commonly used interfaces in the Java Collection Framework. It represents an ordered collection (also known as a sequence) where elements are stored based on their insertion order and can be accessed by their position (index).
Unlike sets, lists allow duplicates, meaning you can store the same element multiple times.
Features
- Ordered: The elements in a List are ordered. That means, the order in which elements are inserted is preserved.
- Indexed: You can access the elements of a List using an index. The index starts from 0, so the first element has an index of 0.
- Allows Duplicates: Unlike sets, Lists allow duplicate elements. You can have more than one occurrence of the same value in the List.
- Flexible Size: Lists in Java are dynamic, meaning they can grow and shrink in size as elements are added or removed.
Common Implementations
Java provides several classes that implement the List interface. The most commonly used implementations include:
- ArrayList: A dynamic array implementation that allows for fast random access of elements but can be slower for adding/removing elements in the middle of the list.
- LinkedList: A doubly linked list implementation that provides efficient insertions and deletions at both ends, but slower random access.
- Vector: Similar to ArrayList but synchronized, making it thread-safe, though less commonly used in modern Java.
- Stack: A special case of List, where elements are added and removed according to the last-in-first-out (LIFO) principle.
Common Methods in the List Interface
add(E e)
: Adds the specified element to the list.get(int index)
: Returns the element at the specified position in the list.remove(int index)
: Removes the element at the specified position.size()
: Returns the number of elements in the list.contains(Object o)
: Checks if the list contains the specified element.set(int index, E element)
: Replaces the element at the specified position with the given element.
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
import java.util.*; public class ListExample { public static void main(String[] args) { // Create a list using ArrayList implementation List<String> fruits = new ArrayList<>(); // Adding elements fruits.add("Apple"); fruits.add("Banana"); fruits.add("Orange"); fruits.add("Banana"); // Allows duplicate "Banana" // Accessing elements by index System.out.println("First fruit: " + fruits.get(0)); // Output: Apple // Removing an element (removes the first occurrence of "Banana") fruits.remove("Banana"); // Iterating using enhanced for-loop System.out.println("Fruits after removal:"); for (String fruit : fruits) { System.out.println(fruit); } // Checking if a specific element exists System.out.println("Contains Orange? " + fruits.contains("Orange")); // true // Getting the size of the list System.out.println("Total fruits: " + fruits.size()); // Output: 3 } } |