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:

  1. add(E e) -> Add element
  2. add(int index, E e) -> Insert at position
  3. get(int index) → Get element by index
  4. set(int index, E e) -> Update element
  5. remove(int index) / remove(Object o) → Remove element
  6. size() → Number of elements
  7. contains(Object o) -> Checks if element exists
  8. clear() → Removes all elements
  9. addAll(Collection c) -> Adds all elements from another collection.
  10. removeAll(Collection c) -> Removes all elements that exist in another collection.
  11. retainAll(Collection c) -> Keeps only the elements that exist in another collection (intersection).
  12. isEmpty() -> Checks if the ArrayList is empty.
  13. indexOf(Object o) -> Returns the index of the first occurrence of the element.
  14. lastIndexOf(Object o) -> Returns the index of the last occurrence of the element.subList(int fromIndex, int toIndex)
  15. Returns a part of the list (view).
  16. toArray() -> Converts ArrayList into an array.
  17. clone() -> Creates a shallow copy of the ArrayList.

Similar Posts