DEV Community

KIRAN RAJ
KIRAN RAJ

Posted on

ArrayList Methods in Java

ArrayList Methods in Java

When I first started learning Java, arrays were a bit confusing because of fixed size. Then I came across ArrayList, and it felt much easier to use.

Basically, ArrayList is like an improved version of array. You don’t need to decide the size before. It grows when you add data.


What is ArrayList?

ArrayList is a class in Java used to store multiple values. It allows duplicate values and keeps order.

In simple terms,
it is just a dynamic array.


Creating an ArrayList

import java.util.ArrayList;

ArrayList<String> list = new ArrayList<>();
Enter fullscreen mode Exit fullscreen mode

Methods I used the most

add()

This is the first method everyone uses. It just adds elements.

list.add("Apple");
list.add("Banana");
Enter fullscreen mode Exit fullscreen mode

Also we can add using index:

list.add(1, "Mango");
Enter fullscreen mode Exit fullscreen mode

get()

Used to take value from list.

System.out.println(list.get(0));
Enter fullscreen mode Exit fullscreen mode

Index starts from 0, same like array.


set()

If you want to change something:

list.set(1, "Orange");
Enter fullscreen mode Exit fullscreen mode

It replaces the old value.


remove()

Used to delete.

list.remove(0);
list.remove("Apple");
Enter fullscreen mode Exit fullscreen mode

Both ways will work.


size()

To know how many elements are there:

System.out.println(list.size());
Enter fullscreen mode Exit fullscreen mode

contains()

Sometimes we need to check if item is present.

System.out.println(list.contains("Banana"));
Enter fullscreen mode Exit fullscreen mode

isEmpty()

Simple check:

System.out.println(list.isEmpty());
Enter fullscreen mode Exit fullscreen mode

clear()

Deletes everything.

list.clear();
Enter fullscreen mode Exit fullscreen mode

Looping

Normal for loop:

for (int i = 0; i < list.size(); i++) {
    System.out.println(list.get(i));
}
Enter fullscreen mode Exit fullscreen mode

For-each (easy one):

for (String s : list) {
    System.out.println(s);
}
Enter fullscreen mode Exit fullscreen mode

Small program I tried

import java.util.ArrayList;

public class Demo {
    public static void main(String[] args) {

        ArrayList<String> list = new ArrayList<>();

        list.add("Tea");
        list.add("Coffee");
        list.add("Boost");

        list.remove("Coffee");

        for (String s : list) {
            System.out.println(s);
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Final

ArrayList is very useful. Once you start using it, you won’t feel like going back to arrays for most cases.

At first I just memorized methods, but later when I practiced, it became easy.

That’s it. Nothing big. Just practice


Top comments (0)