Java 9 ArrayList add, set and remove element
Java ArrayList has useful methods for adding, setting and removing new elements:
- list.add("Bing");
- list.set(0, "DuckDuckGo");
- list.remove(2);
You can check also:
Adding new element to ArrayList Java
ArrayList is dynamic unlike Array and you can add elements dynamically:
import java.util.ArrayList;
ArrayList<String> list = new ArrayList<>();
list.add("Yahoo"); // [0]
list.add("Google"); // [1]
list.add("Bing"); // [2]
result:
Yahoo
Bing
Set new value to ArrayList Java
You can set new values to ArrayList by index:
import java.util.ArrayList;
ArrayList<String> list = new ArrayList<>();
list.add("Yahoo"); // [0]
list.add("Google"); // [1]
list.add("Bing"); // [2]
list.set(0, "DuckDuckGo");
list.set(1, "Baidu");
list.set(2, "Yandex");
result:
DuckDuckGo
Baidu
Yandex
Note: If you give an not existing index in the array you will get: > java.lang.IndexOutOfBoundsException: Index: 1, Size: 1
Remove item from ArrayList by index
Deleting ArrayList item is easy but could be tricky:
import java.util.ArrayList;
ArrayList<String> list = new ArrayList<>();
list.add("Yahoo"); // [0]
list.add("Google"); // [1]
list.add("Bing"); // [2]
list.remove(0);
list.remove(1);
for (String value : list) {
System.out.println(value);
}
result:
Note: In this example we are deleting [0] and [1] but at the end we get: Google which is item - 1. This is because the second remove is applied on changed ArrayList. If you want to delete [0] and [1] of the original list you have to delete [0] twice.
Again wrong index produce error:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 2, Size: 2
Remove item from ArrayList by value
You can remove element by value (in case of non existing value then nothing is changed to ArrayList):
import java.util.ArrayList;
ArrayList<String> list = new ArrayList<>();
list.add("Yahoo");
list.add("Google");
list.add("Bing");
list.remove("Yahoo");
list.remove("Google");
for (String value : list) {
System.out.println(value);
}
result:
Bing