假设以下是带有元素的列表-
ArrayList < String > arrList = new ArrayList < String > (); arrList.add("Jack"); arrList.add("Tom"); arrList.add("Brad"); arrList.add("Amy"); arrList.add("Ben"); arrList.add("Peter"); arrList.add("Katie"); arrList.add("Tim");
现在,使用listIterator()
。该next()
方法返回列表中的下一个元素。悬停,使用remove()
方法删除元素-
ListIterator<String>iterator = arrList.listIterator(); iterator.next(); iterator.remove();
import java.util.ArrayList; import java.util.ListIterator; public class Demo { public static void main(String[] args) { ArrayList<String>arrList = new ArrayList<String>(); arrList.add("Jack"); arrList.add("Tom"); arrList.add("Brad"); arrList.add("Amy"); arrList.add("Ben"); arrList.add("Peter"); arrList.add("Katie"); arrList.add("Tim"); System.out.println("List..."); for (String str: arrList) { System.out.println(str); } ListIterator<String>iterator = arrList.listIterator(); iterator.next(); iterator.remove(); System.out.println("Updated List..."); for (String str: arrList) { System.out.println(str); } } }
输出结果
List... Jack Tom Brad Amy Ben Peter Katie Tim Updated List... Tom Brad Amy Ben Peter Katie Tim