You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
1. Unlike a regular array, an ArrayList can grow and shrink as elements are added or removed.
11
+
This dynamic resizing is achieved by creating a new array and copying the elements to the new array.
12
+
13
+
2. Internally, the ArrayList is implemented as an array of Object references.
14
+
When you add elements to an ArrayList, you're essentially storing these elements in this internal array.
15
+
16
+
3. When you create an ArrayList, it has an initial capacity (default is 10).
17
+
The capacity refers to the size of the internal array that can hold elements before needing to resize.
18
+
19
+
4. When we add an element to an ArrayList, the following steps occur:
20
+
- Check Capacity: Before adding the new element, ArrayList checks if there is enough space in the internal array (elementData). If the array is full, it needs to be resized.
21
+
- Resize if Necessary: If the internal array is full, ArrayList creates a new array with a larger capacity (usually 1.5 times the current capacity) and copies the elements from the old array to the new array.
22
+
- Add the Element: The new element is then added to the internal array at the appropriate index, and the size of the ArrayList is incremented.
23
+
24
+
5. Resizing the Array:
25
+
- Initial Capacity: By default, the initial capacity is 10. This means the internal array can hold 10 elements before it needs to grow.
26
+
- Growth Factor: When the internal array is full, a new array is created with a size 1.5 times the old array. This growth factor balances memory efficiency & resizing cost.
27
+
- Copying Elements: When resizing occurs, all existing elements are copied from the old array to the new array, which is O(n) operation, where n is the number of elements in the ArrayList.
28
+
29
+
6. Removing Elements:
30
+
- Check Bounds: The ArrayList first checks if the index is within the valid range.
31
+
- Remove the Element: The element is removed, and all elements to the right of the removed element are shifted one position to the left to fill the gap.
32
+
- Reduce Size: The size of the ArrayList is decremented by one.
33
+
*/
34
+
35
+
publicclassLearnArrayList {
36
+
publicstaticvoidmain(String[] args) {
37
+
/*
38
+
ArrayList <Integer> list = new ArrayList<>(); // size = 0, capacity = 10
0 commit comments