Java ArrayList.remove() Method Guide
The ArrayList.remove() method is used to remove an element from an ArrayList. Its syntax is:
arrayList.remove(index);
The ‘index’ represents the position of the element to be deleted. Remember, the index of an ArrayList starts from 0, so the index of the first element is 0, the second element is 1, and so on.
For example, if we have an ArrayList that stores some strings:
ArrayList<String> list = new ArrayList<>();
list.add("apple");
list.add("banana");
list.add("cherry");
We can use the remove() method to delete elements at a specific position.
list.remove(1); // 删除第二个元素,即"banana"
The current elements in the list are [“apple”, “cherry”].
To remove elements based on their values, you can use the remove(Object obj) method.
list.remove("apple"); // 删除值为"apple"的元素
The elements in the list now are [“cherry”].
It is important to note that an IndexOutOfBoundsException will be thrown if the specified index is out of bounds or if the specified element does not exist in the ArrayList. Therefore, it is necessary to ensure that the index or element value passed to the remove() method is valid.