Add Element to Java ArrayList

To add an element or object to Java ArrayList, use ArrayList.add() method. ArrayList.add(element) method appends the element or object to the end of ArrayList.

Reference to Syntax and Examples – ArrayList.add().

Example 1 – Add Element to ArrayList

In the following example, we will create an empty ArrayList and then add elements to it using ArrayList.add() method.

Java Program

import java.util.ArrayList;

public class Example {
	public static void main(String[] args) {
		ArrayList<String> arrayList = new ArrayList<String>();  
		arrayList.add("a");  
		arrayList.add("b");  
		arrayList.add("c"); 
		arrayList.add("d");
		arrayList.add("e");
		System.out.println("ArrayList  : " + arrayList);
	}
}

Output

ArrayList  : [a, b, c, d, e]
ADVERTISEMENT

Example 2 – Add Object to ArrayList

In the following example, we will create an ArrayList of Car objects, and add Car objects to the list.

Java Program

import java.util.ArrayList;

public class ArrayListExample {
	public static void main(String[] args) {
		ArrayList<Car> cars = new ArrayList<Car>();
		cars.add(new Car("BMW", 52400));
		cars.add(new Car("Toyota", 66000));
		cars.add(new Car("Audi", 44000));
		
		for(Car car: cars) {
			car.printDetails();
		}
	}
}

class Car {
	public String name;
	public int miles;
	
	public Car(String name, int miles) {
		this.name = name;
		this.miles = miles;
	}
	
	public void printDetails() {
		System.out.println(name + " travelled " + miles + " miles.");
	}
}

Output

BMW travelled 52400 miles.
Toyota travelled 66000 miles.
Audi travelled 44000 miles.

cars.add(new Car("BMW", 52400)); adds the new Car object to the ArrayList of cars.

Conclusion

In this Java Tutorial, we learned how to add element or object to ArrayList in Java.