An ArrayList is used to hold many items of the same type. The main difference between an Array and an ArrayList is that an ArrayList's size is not fixed. Items can be easily added or removed from an ArrayList.
To create an empty list of Strings to hold our planets we can do the following:
ArrayList<String> planets = new ArrayList<String>();
If you wanted the list to hold numbers, you can change String to int.
To add some planets to our list:
planets.add("Mercury"); planets.add("Venus"); planets.add("Earth");
To find out how many items are in the ArrayList, use can use the size method:
System.out.print(planets.size());
To get an item at a specific position, we use the get() method. The items start at zero so to get the first item:
System.out.print(planets.get(0));
One of the main advantages of using arrays instead of using multiple variables is that you can use loops to go through arrays.
To print the items in the list using the size() and get() methods, we can do the following:
for(int c=0;c<planets.size();c++){ System.out.println(planets.get(c)); }
A much simpler way though the list is with a foreach loop, sometimes referred to as an 'enhanced' for loop.
// Each value is taken from the planet list and put into the 'p' variable. // 'var' means we let the compiler figure out the data type (String) for(var p:planets){ System.out.println(num); }
We can remove specific items using their position with the remove() method, to remove the first item in the list:
planets.remove(0);
To remove all items individually, we could use:
for(int c=0;c<planets.size();c++){ planets.remove(c); }
A much shorter method to remove all items is:
planets.clear();
With the Java JDK installed, from a command line:
import java.util.ArrayList; class Planets{ public static void main(String[] args){ ArrayList<String> planets = new ArrayList<String>(); // Add two planets planets.add("Venus"); planets.add("Earth"); planets.add("Ceres"); // Add at the beginning planets.add(0,"Mercury"); // Remove the last item, size() is 4 (0 to 3) so we subtract 1 planets.remove(planets.size()-1); // Modify the 2nd item planets.set(2, "Earth 1"); for(var p:planets){ System.out.println(p); } System.out.println(planets.size()+" Planets"); } }
Updated (08/05/2025)