HOME HTML EDITOR C JAVA PHP

Java ArrayList Methods

In Java, an ArrayList is a part of the Collection Framework. It is used to store dynamic data. Unlike arrays, the size of an ArrayList can grow or shrink automatically.

ArrayList belongs to the java.util package. So, we need to import it before using it.

1. Importing ArrayList

import java.util.ArrayList;

2. Creating an ArrayList

We create an ArrayList using the following syntax:

ArrayList names = new ArrayList();

Here, String is the data type stored in the ArrayList.

3. add()

The add() method is used to add elements to the ArrayList.

names.add("Rahul"); names.add("Amit"); names.add("Neha"); System.out.println(names);

Output: [Rahul, Amit, Neha]

4. add(index, element)

This method inserts an element at a specific position.

names.add(1, "Priya"); System.out.println(names);

5. get()

The get() method returns the element at a specific index.

System.out.println(names.get(0));

6. set()

The set() method changes an element at a specific index.

names.set(0, "Karan"); System.out.println(names);

7. remove()

The remove() method removes an element from the ArrayList.

names.remove(1); System.out.println(names);

You can also remove by value:

names.remove("Neha");

8. size()

The size() method returns the number of elements in the ArrayList.

System.out.println(names.size());

9. contains()

The contains() method checks whether an element exists in the ArrayList.

System.out.println(names.contains("Amit"));

10. clear()

The clear() method removes all elements from the ArrayList.

names.clear(); System.out.println(names);

11. isEmpty()

The isEmpty() method checks if the ArrayList is empty.

System.out.println(names.isEmpty());

12. indexOf() and lastIndexOf()

indexOf() returns the first occurrence of an element. lastIndexOf() returns the last occurrence.

ArrayList list = new ArrayList(); list.add("Java"); list.add("Python"); list.add("Java"); System.out.println(list.indexOf("Java")); System.out.println(list.lastIndexOf("Java"));

13. sort()

We can sort an ArrayList using Collections.sort().

import java.util.Collections; ArrayList numbers = new ArrayList(); numbers.add(5); numbers.add(1); numbers.add(8); Collections.sort(numbers); System.out.println(numbers);

Why ArrayList is Better than Array?

Conclusion

The ArrayList class provides many useful methods like add(), remove(), get(), set(), size(), and more.

It is widely used in real-world Java applications because it is flexible and easy to use.

Tip: Use ArrayList when you need a resizable array and frequent data manipulation.