YouTip LogoYouTip

Java Arraylist Add

# Java ArrayList add() Method [![Image 3: Java ArrayList](#) Java ArrayList](#) The add() method inserts an element into a dynamic array at a specified position. The syntax for the add() method is: arraylist.add(int index, E element) **Note:** arraylist is an object of the ArrayList class. **Parameter Explanation:** * index (optional parameter) - Represents the index value where the element is to be inserted * element - The element to be inserted If the index is not passed as an actual parameter, the element will be appended to the end of the array. ### Return Value Returns true if the element is successfully inserted. Note: If the index is out of range, the add() method throws an IndexOutOfBoundsException. ### Example Using the ArrayList add() method to insert elements: ## Example import java.util.ArrayList; class Main { public static void main(String[] args){ // Create an array ArrayList primeNumbers =new ArrayList(); // Insert elements into the array primeNumbers.add(2); primeNumbers.add(3); primeNumbers.add(5); System.out.println("ArrayList: "+ primeNumbers); } } Executing the above program outputs: ArrayList: [2, 3, 5] In the example above, we created an array named primeNumbers. Here, the optional parameter index was not passed in the add() method. Therefore, all elements are inserted at the end of the array. Inserting an element at a specified position: ## Example import java.util.ArrayList; class Main { public static void main(String[] args){ // Create an array ArrayList sites =new ArrayList(); // Insert elements at the end of the array sites.add("Google"); sites.add(""); 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); } } Executing the above program outputs: ArrayList: [Google, , Taobao]Updated ArrayList: [Google, Weibo, , Taobao] In the example above, 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 array index value of 1. **Note:** So far, we have only added single elements. 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, visit [Java ArrayList addAll()](#). [![Image 4: Java ArrayList](#) Java ArrayList](#)
← Python3 String SwapcasePython3 String Split β†’