ArrayList add() method example

ArrayList add() method is used to add an element in the list. We can add elements of any type in arraylist, but make program behave in more predicatable manner, we should add elements of one certain type only in any goven list instance.

Use generics for compile time type safety while adding the element to arraylist.

1. ArrayList add() syntax

add() method first ensures that there is sufficient space in the arraylist. If list does not have space, then it grows the list by adding more spaces in underlying array. Then it add the element to specific array index.

ArrayList add method implementation is given below.

 public boolean add(E e) {
    ensureCapacityInternal(size + 1);  // Increments modCount!!
    elementData[size++] = e;
    return true;
}
  • Method parameter – The element to be added to this list.
  • Method returns true if element is added.
  • Method throws – no exception is thrown.

2. ArrayList add() example

Java program to add a single element at a time in arraylist using add() method.

2.1. Type-safe arraylist using generics

Always use generics to ensure you add only a certain type of element in a given list.

//ArrayList with generics
ArrayList<String> names = new ArrayList<>();

names.add("alex");
names.add("brian");
names.add("charles");

System.out.println(names);

Program output.

[alex, brian, charles]

2.2. Arraylist without type safety

We can add any type of object in list. This is not recommended.

//ArrayList without generics
ArrayList ages = new ArrayList();

ages.add("1");
ages.add("2");
ages.add(3);
ages.add(new Long(4l));

System.out.println(ages);

Program output.

[1, 2, 3, 4]

Happy Learning !!

Read More:

A Guide to Java ArrayList
ArrayList Java Docs

Leave a Reply

2 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions, and frequently asked interview questions.