Java LinkedList remove() 方法
示例
從列表中移除專案
import java.util.LinkedList;
public class Main {
public static void main(String[] args) {
LinkedList<String> cars = new LinkedList<String>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
cars.add("Mazda");
cars.remove(0);
System.out.println(cars);
}
}
定義和用法
remove()
方法透過位置或值從列表中移除專案。如果指定了位置,則此方法返回被移除的專案。如果指定了值,則如果找到了該值,則返回 true
,否則返回 false
。
如果指定了值,並且列表中有多個元素具有相同的值,則只刪除第一個。
如果列表包含整數,並且您想根據其值刪除一個整數,則需要傳遞一個 Integer
物件。有關示例,請參閱下面的“更多示例”。
語法
以下之一
public T remove(int index)
public boolean remove(Object item)
T
指的是列表中項的資料型別。
引數值
引數 | 描述 |
---|---|
index | 必需。要刪除的專案的位置。 |
item | 必需。要刪除的專案的值。 |
技術詳情
返回 | 如果傳遞了一個物件作為引數,則如果該物件在列表中找到,則返回 true ,否則返回 false。如果傳遞了一個索引,則返回被刪除的物件。 |
---|---|
丟擲 | IndexOutOfBoundsException - 如果索引小於零,等於列表大小或大於列表大小。 |
更多示例
示例
按位置和值從列表中移除整數
import java.util.LinkedList; public class Main { public static void main(String[] args) { LinkedList<Integer> list = new LinkedList<Integer>(); list.add(5); list.add(8); list.add(9); list.add(1); list.remove(Integer.valueOf(1)); // Remove by object list.remove(1); // Remove by index System.out.println(list);
}}
相關頁面
❮ LinkedList 方法