Java ArrayList add() Method
The add() method inserts an element into the dynamic array at the specified position.
The syntax of the add() method is:
arraylist.add(int index,E element)
Note:arraylist is an object of the ArrayList class.
Parameter Details:
- index (optional parameter) - represents the index value at which the element is inserted
- element - the element to be inserted
If the index is not passed as an actual argument, the element will be appended to the end of the array.
Return Value
Returns true if the element is inserted successfully.
Note: If the index is out of range, the add() method throws an IndexOutOfBoundsException.
Example
Insert elements using the ArrayList add() method:
Example
class Main {
public static void main(String[] args) {
// Create an array
ArrayList<Integer> primeNumbers = new ArrayList<>();
// Insert elements into the array
primeNumbers.add(2);
primeNumbers.add(3);
primeNumbers.add(5);
System.out.println("ArrayList: " + primeNumbers);
}
}
The output of the above program is:
ArrayList: [2, 3, 5]
In the above example, we created an array named primeNumbers. Here, the optional parameter index is not passed in the add() method. Therefore, all elements are inserted at the end of the array.
Insert an element at the specified position:
Example
class Main {
public static void main(String[] args) {
// Create an array
ArrayList<String> sites = new ArrayList<>();
// Insert elements at the end of the array
sites.add("Google");
sites.add("Example");
sites.add("Taobao");
System.out.println("ArrayList: " + sites);
// Insert an element at the first position
sites.add(1, "Weibo");
System.out.println("Updated ArrayList: " + sites);
}
}
The output of the above program is:
ArrayList: [Google, Example, Taobao] 更新 ArrayList: [Google, Weibo, Example, Taobao]
In the above example, we used the add() method to insert elements into the array.
Please note this line:
sites.add(1, "Weibo");
We already know that the index parameter in the add() method is optional. So Weibo is inserted at the position with array index value 1.
Note:So far, we have only added a single element. However, we can also use the addAll() method to add multiple elements from a collection (arraylist, set, map, etc.) to an array. To learn more, please visitJava ArrayList addAll() 。
Other Extensions
Java ArrayList