The List interface in Java extends the Collection interface and represents an ordered collection of elements that allows duplicates. It provides methods to access, insert, delete, and manipulate elements by their index.
1. Key Implementations of List
Class
Description
ArrayList
Dynamic array (fast random access, slower insertions/deletions in the middle).
LinkedList
Doubly-linked list (fast insertions/deletions, slower random access).
Vector
Legacy synchronized version of ArrayList (thread-safe but slower).
Stack
Extends Vector (LIFO structure with push(), pop(), peek()).
2. List Interface Methods (Detailed)
📌 Basic Operations
Method
Description
Example
boolean add(E e)
Appends an element to the end of the list.
list.add("Java");
void add(int index, E e)
Inserts an element at a specified position.
list.add(1, "Python");
E get(int index)
Returns the element at the specified position.
String lang = list.get(0);
E set(int index, E e)
Replaces the element at the given index.
list.set(1, "C++");
E remove(int index)
Removes and returns the element at the index.
String removed = list.remove(0);
boolean remove(Object o)
Removes the first occurrence of the object.
list.remove("Java");
int size()
Returns the number of elements.
int len = list.size();
boolean isEmpty()
Checks if the list is empty.
if (list.isEmpty()) {...}
void clear()
Removes all elements.
list.clear();
boolean contains(Object o)
Checks if the element exists.
if (list.contains("Java")) {...}
📌 Bulk Operations (Working with Multiple Elements)
Method
Description
Example
boolean addAll(Collection<? extends E> c)
Adds all elements from another collection.
list.addAll(otherList);
boolean addAll(int index, Collection<? extends E> c)
Inserts all elements at a given position.
list.addAll(1, otherList);
boolean removeAll(Collection<?> c)
Removes all elements present in the given collection.
list.removeAll(toRemove);
boolean retainAll(Collection<?> c)
Keeps only elements present in the given collection.
list.retainAll(toKeep);
📌 Search & Index Operations
Method
Description
Example
int indexOf(Object o)
Returns the first index of the element (or -1 if not found).
int idx = list.indexOf("Java");
int lastIndexOf(Object o)
Returns the last index of the element (or -1).
int lastIdx = list.lastIndexOf("Java");
📌 Sublist & List Iteration
Method
Description
Example
List<E> subList(int fromIndex, int toIndex)
Returns a view of the portion of the list.
List<String> sub = list.subList(1, 3);
Iterator<E> iterator()
Returns an iterator for sequential access.
Iterator<String> it = list.iterator();
ListIterator<E> listIterator()
Returns a bidirectional iterator (supports hasPrevious(), previous()).
Top comments (0)