Java ArrayList.remove() 方法及代码示例
按照索引或者元素从数组列表中移除元素.
定义
public E remove(int index)
或
public boolean remove(Object o)
参数
参数类型 | 参数名称 | 参数描述 |
---|---|---|
int | index | 要删除的元素的位置的索引 |
Object | o | 要删除的列表对象 |
类型参数 | E | 数组列表元素的类型 |
返回值
若按索引删除, 则返回被删除的元素.
若按元素删除, 则返回是否成功从列表删除, 若列表包含该元素则返回 true
, 否则返回 false
.
抛出的异常
IndexOutOfBoundsException
index 超出索引范围(index 小于 0 或 index 大于等于 size())
说明
remove(int index) 方法由 List<E>
接口的 remove()
方法指派
remove(int index) 重写了继承自 AbstractList<E>
类的 remove()
方法
remove(Object o) 方法由 Collection<E>
接口的 remove()
方法指派
remove(Object o) 方法由 List<E>
接口的 remove()
方法指派
remove(Object o) 重写了继承自 AbstractCollection<E>
类的 remove()
方法
注意事项
当按元素删除且列表中包含多个相同元素时, remove() 方法会删除第一个遇到的元素并返回 true
.
示例
从数组列表中删除元素的示例
package com.yi21.arraylist; import java.util.ArrayList; public class Yi21ArraysListRemove { public static void main(String[] args) { ArrayList<String> list = new ArrayList<>(); list.add("Hello"); list.add("World"); list.add("World"); list.add("21yi"); System.out.println("删除的元素为: " + list.remove(3)); System.out.println("当遇上了不可确定的元素时, 是否删除成功? " + list.remove("World")); System.out.println("剩余元素数量? " + list.size()); } }
执行结果为 :
删除的元素为: 21yi 当遇上了不可确定的元素时, 是否删除成功? true 剩余元素数量? 2