ArrayList in Java

ArrayList in Java

Differences between array and ArrayList

  1. 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).

  2. 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 use ArrayList<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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class RemoveDemo1 {
public static ArrayList<Integer> removeEven(ArrayList<Integer> list) {
for(int i = 0; i < list.size(); i++) {
if(list.get(i) % 2 != 0) {
list.remove(i);
}
}

return list;
}

public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<>();
list.add(1);
list.add(3);
list.add(2);
list.add(4);

list = removeEven(list);
System.out.println(list);
}
}

However, when we run this class, the result is not as expected:

arraylist_output_1

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
2
3
4
5
6
7
8
9
Before removing:

List : {1,3,2,4}
Index: 0 1 2 3

After removing:

List : {1,3,4}
Index: 0 1 2

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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class RemoveDemo1 {
public static ArrayList<Integer> removeEven(ArrayList<Integer> list) {
for(int i = 0; i < list.size(); i++) {
if(list.get(i) % 2 != 0) {
list.remove(i--); // After removing the element, we push the counter i backward by 1.
}
}

return list;
}

public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<>();
list.add(1);
list.add(3);
list.add(2);
list.add(4);

list = removeEven(list);
System.out.println(list);
}
}

This time we obtain the expected result:

arraylist_output_2