Now that we've worked with arrays, let's introduce ArrayLists. ArrayLists are part of the Java Collections Framework and provide a more flexible way to work with lists of objects. Unlike arrays, ArrayLists can grow or shrink in size dynamically.
-
Open the file called ArrayListDemo.java
in your project directory.
import java.util.ArrayList;
public class ArrayListDemo {
public static void main(String[] args) {
// We'll add our code here
}
}
Note the import
statement at the top. This tells Java that we want to use the ArrayList class in our program.
-
Now, let's create an ArrayList of Strings. Add this line inside the main
method:
ArrayList<String> fruits = new ArrayList<>();
This creates an empty ArrayList that can hold String objects. The <String>
part is called a "generic" and specifies the type of elements the ArrayList will contain.
-
Let's add some elements to our ArrayList. Add these lines:
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Cherry");
The add()
method appends elements to the end of the list.
-
Now, let's print our ArrayList. Add this code:
System.out.println("Fruits in the list:");
for (String fruit : fruits) {
System.out.println(fruit);
}
This uses an enhanced for loop to iterate through the ArrayList, similar to what we did with arrays.
Tips: You can compile and run your program at any time to see the output. Or, you can continue adding more code and run it all at the end.
-
ArrayLists have many useful methods. Let's try a few. Add this code:
System.out.println("\nNumber of fruits: " + fruits.size());
System.out.println("The second fruit is: " + fruits.get(1));
size()
returns the number of elements in the ArrayList, and get(index)
retrieves the element at the specified index.
-
We can also replace elements in an ArrayList using the set()
method. Add this code:
// Before: [Apple, Banana, Cherry]
fruits.set(1, "Blueberry"); // Replaces "Banana" with "Blueberry"
System.out.println("\nAfter replacing the second fruit:");
System.out.println(fruits); // [Apple, Blueberry, Cherry]
set(index, element)
replaces the element at the specified index with a new element. The ArrayList size remains the same.
-
Unlike arrays, ArrayLists allow us to insert elements at any position using the add(index, element)
method. This is different from set()
which we saw earlier. Let's see how add()
works:
// Before: [Apple, Blueberry, Cherry]
fruits.add(1, "Blackberry");
System.out.println("\nAfter inserting Blackberry at index 1:");
System.out.println(fruits);
// After: [Apple, Blackberry, Blueberry, Cherry]
Let's understand what happened:
add(1, "Blackberry")
inserts "Blackberry" at index 1
- The existing elements at index 1 and beyond (Blueberry, Cherry) are automatically shifted one position to the right
- The ArrayList size increases by 1
- This is different from
set()
which would replace the existing element without shifting or changing the size
To help visualize the difference:
// Using add(index, element) - inserts and shifts
fruits.add(1, "Blackberry"); // [Apple, Blackberry, Blueberry, Cherry]
// Using set(index, element) - replaces without shifting
fruits.set(1, "Blackberry"); // [Apple, Blackberry, Cherry]
-
We can also remove elements from an ArrayList. Add this code:
fruits.remove("Cherry");
System.out.println("\nAfter removing Cherry:");
System.out.println(fruits);
This removes the first occurrence of "Cherry" from the ArrayList. When an element is removed, any subsequent elements are shifted to the left to fill the gap.
-
Finally, let's check if certain elements are in our ArrayList:
System.out.println("\nDoes the list contain Apple? " + fruits.contains("Apple"));
System.out.println("Does the list contain Cherry? " + fruits.contains("Cherry"));
The contains()
method checks if the ArrayList contains a specific element and returns a boolean value.
-
Save the file, then compile and run the program:
javac ~/project/ArrayListDemo.java
java -cp ~/project ArrayListDemo
You should see output similar to this:
Fruits in the list:
Apple
Banana
Cherry
Number of fruits: 3
The second fruit is: Banana
After replacing the second fruit:
[Apple, Blueberry, Cherry]
After inserting Blackberry at index 1:
[Apple, Blackberry, Blueberry, Cherry]
After removing Cherry:
[Apple, Blackberry, Blueberry]
Does the list contain Apple? true
Does the list contain Cherry? false
Congratulations! You've now created an ArrayList, added and removed elements, accessed elements by index, and used various ArrayList methods. You've learned the important distinctions between operations like add()
which inserts and shifts elements, and set()
which replaces elements. ArrayLists offer more flexibility than arrays, as they can grow and shrink as needed. This makes them very useful when you don't know in advance how many elements you'll be working with.