Junior
What is an ArrayList?
sobes.tech AI
Answer from AI
ArrayList is a dynamic array in Java, which is part of the Collection Framework. It implements the List interface.
Main characteristics:
- Resizable: The size of the
ArrayListcan dynamically increase or decrease as elements are added or removed. - Index access: Elements are stored in insertion order and accessible by an integer index starting from 0.
- Allows null: It can contain
nullelements. - Allows duplicates: It can contain repeated elements.
- Not synchronized: Not thread-safe by default. For a thread-safe version, you can use
Collections.synchronizedList(new ArrayList<...>()). - Search: Efficient for operations that access elements by index (O(1)).
- Insert/Delete: Insertion and deletion operations can be slow (O(n)), especially at the beginning or middle of the list, as it may require shifting subsequent elements.
Example of creation:
// Example of creating an ArrayList of strings
ArrayList<String> names = new ArrayList<>();
Main methods:
| Method | Description |
|---|---|
add(E e) |
Adds an element to the end of the list |
add(int index, E element) |
Inserts an element at the specified index |
get(int index) |
Returns the element at the specified index |
remove(int index) |
Removes the element at the specified index |
size() |
Returns the number of elements |
isEmpty() |
Checks if the list is empty |
contains(Object o) |
Checks if the list contains the specified element |
clear() |
Removes all elements |