How to Add Element to ArrayList in Java: Simple Guide
To add an
element to an ArrayList in Java, use the add() method. For example, arrayList.add(element); adds the element to the end of the list.Syntax
The basic syntax to add an element to an ArrayList is:
arrayList.add(element);- Addselementto the end of the list.arrayList.add(index, element);- Insertselementat the specifiedindex, shifting later elements.
java
arrayList.add(element); arrayList.add(index, element);
Example
This example shows how to create an ArrayList, add elements to it, and print the list.
java
import java.util.ArrayList; public class AddElementExample { public static void main(String[] args) { ArrayList<String> fruits = new ArrayList<>(); fruits.add("Apple"); fruits.add("Banana"); fruits.add(1, "Orange"); System.out.println(fruits); } }
Output
[Apple, Orange, Banana]
Common Pitfalls
Common mistakes when adding elements to an ArrayList include:
- Using an invalid index with
add(index, element)which causesIndexOutOfBoundsException. - Trying to add
nullelements unintentionally. - Confusing
add()withset(), whereset()replaces an element instead of adding.
java
import java.util.ArrayList; public class PitfallExample { public static void main(String[] args) { ArrayList<String> list = new ArrayList<>(); list.add("A"); // Wrong: adding at index 5 when list size is 1 // list.add(5, "B"); // This throws IndexOutOfBoundsException // Correct way: list.add(1, "B"); // Adds at index 1 System.out.println(list); } }
Output
[A, B]
Quick Reference
| Method | Description |
|---|---|
| add(element) | Adds element to the end of the list |
| add(index, element) | Inserts element at specified index |
| set(index, element) | Replaces element at index (does not add) |
| size() | Returns number of elements in the list |
Key Takeaways
Use arrayList.add(element) to add elements at the end.
Use arrayList.add(index, element) to insert at a specific position.
Avoid invalid indexes to prevent exceptions.
Remember add() inserts, set() replaces elements.
ArrayList can hold null elements but use carefully.