ArrayList
Unlike ordinary arrays, the
ArrayList from the
java.util package is an automatically expanding array. When you create an object of type
ArrayList, you do not need to specify its dimension. For example,
ArrayList list = new ArrayList();
Advantages ArrayList compared to a regular array:
- fast access to elements by index in constant time
O(1);
- access elements by value in linear time
O(n);
- allows you to store any value, including
null.
Weaknesses ArrayList:
Inserting/removing an element causes overwriting of all elements placed "to the right" in the list one position to the left, that is, it works in linear time O(n);
Remember that lists can only contain objects, so if you want to store numbers use Integer instead of int. Integer is the name of a class, and an object of this class can contain an integer value. You can read more about classes and objects here: introduction to object-oriented programming.