Java List Interface
The List
interface is a subtype of the Collection
interface in the Java Collections Framework. It represents an ordered collection of elements where duplicate elements are allowed. The order of elements is determined by their index position in the list. The List
interface provides methods to add, remove, and retrieve elements by their index.
Here are some of the key methods defined in the List
interface:
void add(int index, E element)
: Inserts the specified element at the specified position in the list.boolean addAll(int index, Collection<? extends E> collection)
: Inserts all elements from the specified collection into the list, starting at the specified position.E get(int index)
: Returns the element at the specified position in the list.int indexOf(Object element)
: Returns the index of the first occurrence of the specified element in the list, or -1 if the element is not found.int lastIndexOf(Object element)
: Returns the index of the last occurrence of the specified element in the list, or -1 if the element is not found.ListIterator<E> listIterator()
: Returns aListIterator
over the elements in the list.ListIterator<E> listIterator(int index)
: Returns aListIterator
over the elements in the list, starting at the specified position.E remove(int index)
: Removes the element at the specified position in the list.E set(int index, E element)
: Replaces the element at the specified position in the list with the specified element.List<E> subList(int fromIndex, int toIndex)
: Returns a new list containing the elements between the specified fromIndex, inclusive, and toIndex, exclusive.
Implementations of the List
interface include ArrayList
, LinkedList
, and Vector
. The ArrayList
class provides a resizable array that can be used to store elements, while the LinkedList
class provides a linked list that can be used to store elements. The Vector
class is similar to the ArrayList
class, but is synchronized, which means that it is thread-safe.
By using the methods defined in the List
interface, you can easily manipulate lists of objects and perform common operations such as sorting, searching, and filtering.