9. 11. 14. Removing a Single Element |
|
Use the remove() method to remove a single element: |
- public boolean remove(Object element)
- Removes a single element by checking for equality,
- Returns true if the object was found and removed from the list,
- Otherwise, false is returned.
|
If the list contains duplicates, the first element in the list that matches the element will be removed. |
If removal is not supported, you'll get an UnsupportedOperationException. |
If the index passed in is outside the valid range of elements, an IndexOutOfBoundsException is thrown. |
import java.util.ArrayList;
import java.util.List;
public class MainClass {
public static void main(String args[]) throws Exception {
List list = new ArrayList();
list.add("A");
list.add("B");
list.add("C");
System.out.println(list.remove(0));
System.out.println(list.remove("B"));
System.out.println(list);
}
}
|
|
A
true
[C] |