What is an ArrayList?
An ArrayList is a class in Java that stores a list of items.
It is similar to an array, but it can grow and shrink as needed.
Why Use an ArrayList?
- You do not need to know the size ahead of time.
- You can easily add and remove items.
- It has built-in methods that make it easy to use.
Importing ArrayList
Before using an ArrayList, you must import it:
import java.util.ArrayList;
Creating an ArrayList
Here is how to make an ArrayList of Strings:
ArrayList<String> fruits = new ArrayList<String>();
Here is how to make an ArrayList of Integers:
ArrayList<Integer> numbers = new ArrayList<Integer>();
Important
Notice that Java uses wrapper classes like Integer instead of
int in an ArrayList.
Adding Items
Use add() to put items into the ArrayList:
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Orange");
Displaying the ArrayList
System.out.println(fruits);
Output:
[Apple, Banana, Orange]
Getting an Item
Use get(index) to access one item:
System.out.println(fruits.get(1));
Output:
Banana
Changing an Item
Use set(index, value) to replace an item:
fruits.set(1, "Grapes");
System.out.println(fruits);
Output:
[Apple, Grapes, Orange]
Removing an Item
Use remove(index) to delete an item:
fruits.remove(0);
System.out.println(fruits);
Output:
[Grapes, Orange]
Finding the Size
Use size() to count how many items are in the ArrayList:
System.out.println(fruits.size());
Looping Through an ArrayList
You can use a regular for loop:
for (int i = 0; i < fruits.size(); i++) {
System.out.println(fruits.get(i));
}
You can also use a for-each loop:
for (String fruit : fruits) {
System.out.println(fruit);
}
Common Methods
add(item)– adds an itemget(index)– gets an itemset(index, item)– changes an itemremove(index)– removes an itemsize()– returns the number of itemsclear()– removes all items
Example Program
import java.util.ArrayList;
public class ArrayListExample {
public static void main(String[] args) {
ArrayList<String> students = new ArrayList<String>();
students.add("Alice");
students.add("Brian");
students.add("Carlos");
System.out.println("Student List: " + students);
System.out.println("First Student: " + students.get(0));
students.set(1, "Bella");
students.remove(2);
System.out.println("Updated List: " + students);
System.out.println("Number of Students: " + students.size());
}
}
Summary
- An
ArrayListis a resizable list in Java. - It is useful when you need a list that can change size.
- You can add, remove, replace, and access items easily.
- Use methods like
add(),get(),set(), andremove().