Advertisement
Google Ad Slot: content-top
Java Collection List
In Java, List is an ordered collection that allows duplicate elements and provides indexed access. It is a part of the Java Collections Framework and extends the Collection interface.
Types of Sets in Java
Implementation |
Internal Structure |
Performance |
Best Use Case |
|---|---|---|---|
ArrayList |
Dynamic Array |
Fast for random access |
When searching is frequent |
LinkedList |
Doubly Linked List |
Fast for insertions/deletions |
When insertions/removals are frequent |
Vector |
Dynamic Array (Thread-safe) |
Similar to |
When thread safety is required |
Stack |
LIFO (Last-In-First-Out) |
Push & pop in |
When stack operations are needed |
ArrayList:
LinkedList:
Vector:
vector is child of List Interface so In Vector we can use all List interface fuction with synchronized thread safe(multi thread)
Stack:
Stackis child of Vector Interface and List interface so In Stack we can use all List interface fuction with some extra function like (push,pop,peek)
List Methods:
Commonly Used Methods of List Interface
Method |
Description |
|---|---|
add(Object o) or addLast(Object o) |
Adds an element to the list |
addFirst(Object o) |
Adds an element to the list at first index |
getFirst() |
Returns the element at the first index |
getLast() |
Returns the element at the last index |
get(int index) |
Returns the element at the specified index |
set(int index, Object o) |
Replaces the element at the specified index |
removeFirst() |
Removes the element at the first index |
removeLast() |
Removes the element at the last index |
remove(int index) |
Removes the element at the specified index |
size() |
Returns the number of elements in the list |
contains(Object o) |
Checks if the list contains the specified element |
indexOf(Object o) |
Returns the first index of the element |
isEmpty() |
Checks if the list is empty |
subList(int from, int to) |
Returns a portion of the list |
reversed() |
Returns a reverse of the list |
copy() |
Returns a copied list |
sort() |
Sort the list |
Stack Methods:
All List Interface methods are working in Stack Interface apart from Stack have some extra methods
Method |
Description |
|---|---|
push(Object o) |
Adds an element to the list can use (add(Object o)) |
pop() |
Removes the element at the last index can use (removeLast()) |
peek() |
Returns the element at the last index can use(getLast()) |
empty() |
Checks if the list is empty can use(isEmpty()) |
search(Object o) |
Returns the first index of the element can use(indexOf(Object o)) |