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
AMAN .
Please tell me why this happened?
Output:
Main ArrayList []
after adding sub main arraylist [[4, 5]]
after adding sub main arraylist [[3, 10], [3, 10]]
The main arraylist not contains [4,5] .It contains [3,10] twice.
Then where [4,5] has gone?
Lokesh Gupta
[4,5] gone where you cleared the array list. You have added the same arraylist twice in
main
list. Whatever you do with'sub'
will reflect in both places inmain
list.