Junior
What is an ArrayList?
sobes.tech AI
Answer from AI
ArrayList is a dynamic array in Java, implemented based on a regular array.
Main characteristics:
- Dynamic size: Can grow or shrink as elements are added or removed.
- Indexed access: Elements are accessible by their index (starting from 0).
- Order of elements: Maintains the order of insertion.
- Not thread-safe: Not synchronized; for multi-threaded scenarios,
VectororCollections.synchronizedListare used. - Performance:
- Adding/removing at the end O(1) on average (amortized time).
- Adding/removing in the middle O(n) (requires shifting elements).
- Access by index O(1).
- Element search O(n).
Example usage:
import java.util.ArrayList;
// Creating an ArrayList
ArrayList<String> names = new ArrayList<>();
// Adding elements
names.add("Alice");
names.add("Bob");
names.add("Charlie");
// Accessing an element by index
String firstElement = names.get(0); // "Alice"
// Size of ArrayList
int size = names.size(); // 3
// Removing an element
names.remove("Bob"); // Removes the first found "Bob"
names.remove(0); // Removes the element at index 0 (now "Charlie")
// Iterating over elements
for (String name : names) {
System.out.println(name);
}