There are three ways to remove an element from a ArrayList in Java.
Using remove(index) - This method takes the index of ArrayList and remove the required element from the ArrayList.
Using remove(Object) - This method takes the object of ArrayList and remove it from the ArrayList.
Using Iterator.remove() - This method removes the element without causing ConcurrentModificationException.
import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class Tester{ public static void main(String[] args) { List<Integer> list = new ArrayList<>(); list.add(1); list.add(2); list.add(3); list.add(4); list.add(5); list.add(6); System.out.println(list); //remove by index list.remove(5); System.out.println(list); //remove by Object list.remove(new Integer(5)); //remove using iterator Iterator<Integer> iterator = list.iterator(); while(iterator.hasNext()){ if(iterator.next() == 4){ iterator.remove(); } } System.out.println(list); } }
[1, 2, 3, 4, 5, 6] [1, 2, 3, 4, 5] [1, 2, 3]