Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
How do I add an element to an array list in Java?
We can add elements to an ArrayList easily using its add() method. The method appends the specified element to the end of the list, or inserts it at a specific index.
Syntax
boolean add(E e) void add(int index, E element)
The first form appends the element to the end. The second form inserts the element at the specified index, shifting existing elements to the right.
Example
The following example shows how to add elements to an ArrayList using both forms of the add() method ?
import java.util.ArrayList;
import java.util.List;
public class CollectionsDemo {
public static void main(String[] args) {
List<Integer> list = new ArrayList<>();
// add() - appends to end
list.add(1);
list.add(2);
list.add(3);
list.add(4);
list.add(5);
list.add(6);
System.out.println("List: " + list);
// add(index, element) - inserts at position
list.add(0, 0);
System.out.println("After add(0, 0): " + list);
list.add(3, 99);
System.out.println("After add(3, 99): " + list);
}
}
The output of the above code is ?
List: [1, 2, 3, 4, 5, 6] After add(0, 0): [0, 1, 2, 3, 4, 5, 6] After add(3, 99): [0, 1, 2, 99, 3, 4, 5, 6]
Conclusion
Use add(element) to append an element at the end of the ArrayList, or add(index, element) to insert at a specific position. The add() method always returns true for ArrayList since the operation is always successful.
Advertisements
