List , ArrayList and Methods
List:
A List in Java is an ordered collection from the Collection framework that allows duplicate elements and provides index-based access.
Common implementations are ArrayList, LinkedList, Vector, and Stack.
Key Features of List:
1)Ordered collection → Elements are stored in insertion order.
2)Allows duplicates → Same element can appear more than once.
3)Index-based access → You can access elements using an index (like arrays).
4)Dynamic in size → Unlike arrays, lists can grow or shrink at runtime.
5)Supports CRUD operations → add, remove, update, search, etc.
Common Implementations of List:
- ArrayList → Fast for searching, slow for insertion/deletion in middle.
- LinkedList → Fast for insertion/deletion, slower for searching.
- Vector → Similar to ArrayList but thread-safe.
- Stack → Follows LIFO (Last In First Out) principle.
ArrayList:
An ArrayList in Java is a resizable array implementation of the List interface.
It allows duplicate elements, maintains insertion order, and provides fast index-based access, but is not synchronized by default.
Key features of ArrayList:
- ArrayList is a class in java.util package.
- It is a resizable array implementation of the List interface.
- It stores elements in insertion order.
- It allows duplicate elements.
- It provides index-based access to elements.
Commonly Used Methods:
- add(E e) -> Add element
- add(int index, E e) -> Insert at position
- get(int index) → Get element by index
- set(int index, E e) -> Update element
- remove(int index) / remove(Object o) → Remove element
- size() → Number of elements
- contains(Object o) -> Checks if element exists
- clear() → Removes all elements
- addAll(Collection c) -> Adds all elements from another collection.
- removeAll(Collection c) -> Removes all elements that exist in another collection.
- retainAll(Collection c) -> Keeps only the elements that exist in another collection (intersection).
- isEmpty() -> Checks if the ArrayList is empty.
- indexOf(Object o) -> Returns the index of the first occurrence of the element.
- lastIndexOf(Object o) -> Returns the index of the last occurrence of the element.subList(int fromIndex, int toIndex)
- Returns a part of the list (view).
- toArray() -> Converts ArrayList into an array.
- clone() -> Creates a shallow copy of the ArrayList.