Java的List容器使用remove()方法时应注意int和Integer的区别!!

本文探讨了在实现Prim算法过程中遇到的问题:使用ArrayList存储节点索引并尝试移除元素时引发IndexOutOfBoundsException异常的原因。文章详细解释了ArrayList的remove方法重载特性可能导致的误解,并给出了正确的元素移除方式。

今天我在写最小生成树的Prim算法的时候,发现了一个问题,我觉得值得探讨一下:
我使用一个ArrayList储存未加入最小生成树的节点的index(整数类型),每一次循环找到一个离已加入最小生成树的节点集合“最近”的节点,将它的index从这个ArrayList中删除。在检查程序逻辑无误后运行,发现抛出了java.lang.IndexOutOfBoundsException

原因

简单检查后我发现ArrayList的remove方法是一个重载的(overloaded)方法。即:
这里写图片描述
从IDEA的代码提示可以看到,remove方法有两种参数类型,一种是int类型,一种是Object类型。如果你的ArrayList指定的元素类型是Integer,那么你使用remove方法移除一个Integer类型的元素的时候,程序可能理解成移除由该数字指定位置上的元素。
我进一步猜想线性容器应当都有通过index删除元素的方法,因此我查看了List接口的定义,其中果不其然有两个remove方法:
1. 按index移除元素:

E remove(int index);


    // Search Operations

    /**
     * Returns the index of the first occurrence of the specified element
     * in this list, or -1 if this list does not contain the element.
     * More formally, returns the lowest index <tt>i</tt> such that
     * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>,
     * or -1 if there is no such index.
     *
     * @param o element to search for
     * @return the index of the first occurrence of the specified element in
     *         this list, or -1 if this list does not contain the element
     * @throws ClassCastException if the type of the specified element
     *         is incompatible with this list
     *         (<a href="Collection.html#optional-restrictions">optional</a>)
     * @throws NullPointerException if the specified element is null and this
     *         list does not permit null elements
     *         (<a href="Collection.html#optional-restrictions">optional</a>)
     */

2.按元素移除:

boolean remove(Object o);


    // Bulk Modification Operations

    /**
     * Returns <tt>true</tt> if this list contains all of the elements of the
     * specified collection.
     *
     * @param  c collection to be checked for containment in this list
     * @return <tt>true</tt> if this list contains all of the elements of the
     *         specified collection
     * @throws ClassCastException if the types of one or more elements
     *         in the specified collection are incompatible with this
     *         list
     * (<a href="Collection.html#optional-restrictions">optional</a>)
     * @throws NullPointerException if the specified collection contains one
     *         or more null elements and this list does not permit null
     *         elements
     *         (<a href="Collection.html#optional-restrictions">optional</a>),
     *         or if the specified collection is null
     * @see #contains(Object)
     */

解决

因此,在编程的时候,应当严格区分Integer和int。如果你要从一个元素类型为Integer的List中删除一个元素(按照元素而不是index删除),你应该用以下两种方式的其中一种:

int elementToBeRemoved = 0;
list.remove((Integer)elementToBeRemoved);

Integer elementToBeRemoved = 0;
list.remove(elementToBeRemoved);

### Java List Remove Method Return Value 在 Java 中,`List` 接口提供了多种 `remove` 方法重载版本。对于不同类型的参数输入,这些方法有着不同的行为返回值。 当通过索引调用 `remove(int index)` 方法,此操作会移除列表中指定位置上的元素并将其作为返回值[^1]: ```java // 创建一个包含一些整数的列表 List<Integer> numbers = Arrays.asList(1, 2, 3, 4); numbers = new ArrayList<>(numbers); Integer removedElement = numbers.remove(0); // 移除第一个元素 System.out.println("Removed element is: " + removedElement); // 输出被移除的元素 ``` 如果使用的是带有对象参数的 `remove(Object o)` 方法,则该函数尝试从列表中找到并移除首次出现的对象实例,并返回布尔值表示是否成功找到了要移除的目标项: ```java String itemToRemove = "apple"; boolean wasRemoved = fruitList.remove(itemToRemove); if (wasRemoved) { System.out.println("Item '" + itemToRemove + "' has been successfully removed."); } else { System.out.println("Could not find the specified item to remove."); } ``` 需要注意,在遍历直接调用 `remove()` 可能引发并发修改异常 (`ConcurrentModificationException`),这是因为迭代器检测到了未预期到结构化更改所致[^4]。为了避免这种情况发生,建议采用显式的迭代器来完成删除动作: ```java Iterator<String> iterator = stringList.iterator(); while (iterator.hasNext()) { String current = iterator.next(); if (someCondition(current)) { iterator.remove(); // 安全地移除当前元素 } } ```
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值