ArrayList
, please note the following points:
ArrayList
internally uses a dynamic array (Object[] elementData
) to store its elements.
ArrayList
.
ArrayList
:
ArrayList
works internally:
ArrayList
as follows: ArrayList<Integer> list = new ArrayList<>();
ArrayList
object is created with an initial capacity of 10 and a size of 0. This means it can hold up to 10 elements initially, but no elements have been added yet. add()
method:list.add(10);
list.add(20);
list.add(30);
list.add(40);
list.add(110)
), the ArrayList
automatically resizes.
newCapacity = (oldCapacity * 3) / 2 + 1
oldCapacity = 10
newCapacity = (10 * 3) / 2 + 1 = 16
ArrayList
now points to the new array, while the old array becomes unreferenced and eligible for garbage collection. ArrayList
. We can only obtain the current size using list.size()
.
ArrayList
allows duplicate elements and null values.
get(int index)
):
set(int index, E element)
):
add(E e)
):
add(int index, E element)
):
remove(int index)
):
contains
, indexOf
):
Operation | Performance | Complexity |
---|---|---|
Access by index (get) |
Very Fast | O(1) |
Update by index (set) |
Very Fast | O(1) |
Add at end (add) |
Fast | O(1) amortized |
Insert in middle/start (add(i)) |
Slow | O(n) |
Remove by index/value |
Slow | O(n) |
Search (contains, indexOf) |
Slow | O(n) |
Iteration |
Fast | O(n) but cache-friendly |
Your feedback helps us grow! If there's anything we can fix or improve, please let us know.
We’re here to make our tutorials better based on your thoughts and suggestions.