可以使用ListIterator方法从ArrayList中删除元素remove()
。此方法删除ArrayList中的当前元素。如果该remove()
方法之前没有该next()
方法,则抛出IllegalStateException异常。
演示该程序的程序如下。
import java.util.ArrayList; import java.util.ListIterator; public class Demo { public static void main(String[] args) { ArrayList<String> aList = new ArrayList<String>(); aList.add("Apple"); aList.add("Mango"); aList.add("Guava"); aList.add("Orange"); aList.add("Peach"); System.out.println("The ArrayList elements are: "); for (String s: aList) { System.out.println(s); } ListIterator li = aList.listIterator(); li.next(); li.remove(); System.out.println("\nThe element Apple is removed"); System.out.println("\nThe ArrayList elements are: "); for (String s: aList) { System.out.println(s); } } }
输出结果
上面程序的输出如下-
The ArrayList elements are: Apple Mango Guava Orange Peach The element Apple is removed The ArrayList elements are: Mango Guava Orange Peach