0% completed
The List interface is a cornerstone of the Java Collections Framework. It represents an ordered collection (also known as a sequence) that can contain duplicate elements. Lists allow you to access elements by their numerical index, making it easy to retrieve, update, or remove items based on their position. This interface is designed for scenarios where the order of insertion matters.
The List interface is declared in the java.util
package and extends the Collection interface. Here’s how it looks in its simplest form:
public interface List<E> extends Collection<E> { // Method declarations for list operations }
public interface List<E>
:List
interface is generic, where E
represents the type of elements stored in the list.extends Collection<E>
:get(int index)
, set(int index, E element)
).get(0)
.Below is a table that highlights some of the key methods available in the List interface along with a brief description:
Method | Description |
---|---|
add(E e) | Appends the specified element to the end of the list. |
add(int index, E element) | Inserts the specified element at the specified position in the list. |
get(int index) | Returns the element at the specified position in the list. |
set(int index, E element) | Replaces the element at the specified position with the specified element. |
remove(int index) | Removes the element at the specified position. |
indexOf(Object o) | Returns the index of the first occurrence of the specified element, or -1 if not found. |
size() | Returns the number of elements in the list. |
clear() | Removes all elements from the list. |
Common implementations of the List interface include:
The List interface is a versatile and fundamental part of the Java Collections Framework. It defines a contract for ordered collections that allow duplicate elements and index-based access. By programming to the List interface, you gain the flexibility to choose the most appropriate list implementation for your needs, whether it’s an ArrayList for fast random access or a LinkedList for frequent modifications.
In the next lesson, we will learn to use the ArrayList class.
.....
.....
.....