ArrayList in Java
ArrayList in Java
Differences between array and ArrayList
When we declare an array, we should specify the capacity of the array(e.g.,
int[] array = new int[10];
). However, we do not need to specify the size when we create an ArrayList. Therefore, if we know the size beforehand, we can use array, which is more efficient. If we do not know the size, we can use ArrayList, which is resizable(the initial capacity is 10, and the capacity grows automatically as elements are added to the list).ArrayList can only hold object, which means we can not have an ArrayList of primitive-type elements. For example, if we write
ArrayList<int>
, the code doesn’t compile. To obtain an ArrayList which stores integers, we should useArrayList<Integer>
.
Remove method in ArrayList
remove()
method can remove the element at the specified position in an ArrayList. It is worth noting that after removing the specified element, this method would shift any subsequent elements to the left (subtracts one from their indices). The following examples can help us fully understand remove()
method.
RemoveDemo1
In this Demo, removeEven()
is used to remove even elements in an ArrayList. For example, if we have an ArrayList {1,3,2,4}
, this method is expected to return {1,3}
.
1 | public class RemoveDemo1 { |
However, when we run this class, the result is not as expected:
The reason is that after removing the 3rd element(which is 2) in the list, the index of the 4th element(which is 4) is changed:
1 | Before removing: |
And in the for-loop, the counter i keeps incresing, which mean the element 4 is skipped.
RemoveDemo2
To address the problem mentioned above, we should make a subtle change to the code:
1 | public class RemoveDemo1 { |
This time we obtain the expected result: