Java如何从LinkedList中删除项目?
该程序向您展示如何使用LinkedList类remove(intindex)方法从链接列表对象中删除指定索引处的项目。
package org.nhooo.example.util; import java.util.LinkedList; public class LinkedListRemove { public static void main(String[] args) { LinkedList<String> names = new LinkedList<>(); names.add("Alice"); names.add("Bob"); names.add("Carol"); names.add("Mallory"); System.out.println("Original values are:"); System.out.println("===================="); for (String name : names) { System.out.println("Name = " + name); } // 从链接列表中删除Carol。 names.remove(2); System.out.println("New values are:"); System.out.println("===================="); for (String name : names) { System.out.println("Name = " + name); } } }
上面程序的结果是:
Original values are: ==================== Name = Alice Name = Bob Name = Carol Name = Mallory New values are: ==================== Name = Alice Name = Bob Name = Mallory