add - Java ArrayList Method
TLDR
Appends an element to the end of a list.
// Method Signature
boolean add(E element)
Usage
The ArrayList add
appends an element to the end of a list.
// Method Signature
boolean add(E element)
// Code Example
// Create an ArrayList of Integers
ArrayList<Integer> list = new ArrayList<>();
// add 2 to list
list.add(2);
// prints [2]
System.out.println(list);
// add 6 to list
list.add(6);
// prints [2, 6]
System.out.println(list);
// add 4 to list
list.add(4);
// prints [2, 6, 4]
System.out.println(list);
In the code example above, we create an Integer ArrayList and use the add
method to append integers to the list. Each add
method call appends an
integer to the end of the list.
Parameters
This method takes one parameter called element
:
element
is appended to the end of the ArrayList.element
should be compatible with the type passed to the ArrayList.
// Parameters Example
// create an ArrayList with a String type
ArrayList<String> list = new ArrayList<>();
// "study" is compatiable with a String
list.add("study");
// prints [study]
System.out.println(list);
// "pain" is added to the end
list.add("pain");
// prints [study, pain]
System.out.println(list);
In the example above, the type passed to the ArrayList is String, so each element must be compatible with the String type.
Returns
The return type of this method is a boolean.
Even though the return type is a boolean, the add
method will always return true.
// Returns Example
// Create an ArrayList with a Double type
ArrayList<Double> list = new ArrayList<>();
// prints true
System.out.println(list.add(5.3));
The boolean return type comes from the Collection Interface that ArrayList
implements. Returning true or false works for other collection types like
Sets, where true is returned if the element is added, and false is returned if
the element already exists. The ArrayList add
method will always add the element, so it only returns true.