首页javalistJava Collection - 如何删除单个元素

Java Collection - 如何删除单个元素

我们想知道如何删除单个元素。

Use the remove() method to remove a single element:

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); } }