The ArrayList class, located in the java.util package, is a dynamically resizable array.
In Java, the distinction between a built-in array and an ArrayList lies in their modifiability: arrays have a fixed size, necessitating the creation of a new array to add or remove elements, whereas an ArrayList allows for dynamic addition and removal of elements. Additionally, their syntax differs slightly.
Instantiate an ArrayList object named “cars” designed to store strings:
import java.util.ArrayList; // import the ArrayList class ArrayList<String> cars = new ArrayList<String>(); // Create an ArrayList object |
If you’re unsure about the concept of a package, you can refer to our Java Packages Tutorial for clarification. |
The ArrayList class provides numerous helpful methods. For instance, to append elements to the ArrayList, utilize the add() method:
import
|
To access an element in the ArrayList, use the get() method and refer to the index number:
|
Keep in mind: Array indexes commence with 0, where [0] denotes the first element, [1] denotes the second element, and so forth. |
To alter an element, employ the set() method and specify the index number:
|
To eliminate an element, utilize the remove() method and specify the index number:
|
To eliminate all elements within the ArrayList, employ the clear() method:
|
To determine the number of elements in an ArrayList, utilize the size() method.
|
Iterate through the elements of an ArrayList using a for loop, specifying the number of iterations based on the size() method:
public |
Another way to iterate through an ArrayList is by using the for-each loop.
public |
Elements stored in an ArrayList are objects. In the previous examples, we instantiated elements (objects) of type “String”. It’s important to note that in Java, a String is an object, not a primitive type. When using other types such as int, you need to specify the equivalent wrapper class, for example, Integer. For other primitive types, use Boolean for boolean, Character for char, Double for double, and so forth
Instantiate an ArrayList to store numbers, adding elements of type Integer.
import
|
Another valuable class within the java.util package is the Collections class, which contains the sort() method for arranging lists alphabetically or numerically.
Arrange an ArrayList of Strings in sorted order.
import
|
Arrange an ArrayList of Integers in sorted order.
import
|