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<>();
Methods I used the most
add()
This is the first method everyone uses. It just adds elements.
list.add("Apple");
list.add("Banana");
Also we can add using index:
list.add(1, "Mango");
get()
Used to take value from list.
System.out.println(list.get(0));
Index starts from 0, same like array.
set()
If you want to change something:
list.set(1, "Orange");
It replaces the old value.
remove()
Used to delete.
list.remove(0);
list.remove("Apple");
Both ways will work.
size()
To know how many elements are there:
System.out.println(list.size());
contains()
Sometimes we need to check if item is present.
System.out.println(list.contains("Banana"));
isEmpty()
Simple check:
System.out.println(list.isEmpty());
clear()
Deletes everything.
list.clear();
Looping
Normal for loop:
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
For-each (easy one):
for (String s : list) {
System.out.println(s);
}
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);
}
}
}
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)