Remove Item from ArrayList
To remove an item from an ArrayList in Java, you can use the remove()
method of the ArrayList class.
The remove()
method takes an index or an object as an argument and removes the element at the specified index, or the first occurrence of the specified object, from the list.
Here is an example of how you can use the remove()
method to remove an item from an ArrayList:
List<String> list = new ArrayList<>(Arrays.asList("item1", "item2", "item3"));
list.remove(1); // removes "item2" from the list
In this example, the remove()
method is used to remove the element at index 1 (the second element) from the list. The resulting list is ["item1", "item3"]
.
You can also use the remove()
method to remove the first occurrence of a specified object from the list:
List<String> list = new ArrayList<>(Arrays.asList("item1", "item2", "item2", "item3"));
list.remove("item2"); // removes the first occurrence of "item2" from the list
In this example, the remove()
method is used to remove the first occurrence of the object "item2" from the list. The resulting list is ["item1", "item2", "item3"]
.
I hope this helps! Let me know if you have any questions.