๐ What is the List Interface?
The List interface in Java is a subinterface of Collection that represents an ordered collection of elements. It allows:
- Duplicate elements
- Access via index
- Maintains insertion order
๐ง Package: java.util.List
โ
Key Features:
-
Indexed access: Elements can be accessed by position (e.g.,
list.get(0)).
- Duplicates allowed
-
Order preserved (elements stay in the order they are added)
๐ง Common Implementations:
| Implementation |
Characteristics |
ArrayList |
Fast for read, slow for insert/delete |
LinkedList |
Fast for insert/delete, slower for read |
Vector |
Synchronized (thread-safe, legacy) |
Stack |
LIFO (Last In First Out) structure |
๐งฐ Common Methods inย List:
| Method |
Description |
add(E e) |
Adds an element at the end |
add(int index, E) |
Adds an element at specified index |
get(int index) |
Returns the element at given index |
remove(int index) |
Removes element at specified index |
set(int index, E) |
Updates element at index |
indexOf(Object o) |
Returns first index of element (or -1) |
size() |
Returns number of elements |
๐ Example:
๐ง Summary:
| Feature |
List Interface |
| Order |
Maintains insertion order |
| Duplicates |
Allowed |
| Access |
By index (zero-based) |
| Use cases |
To-do lists, shopping carts, etc. |