Java中List.remove()方法的bug

本文详细解析了Java中List.remove方法存在的bug,并通过具体代码示例展示了在实际使用过程中可能出现的问题,尤其是当列表中存在与索引相同值的元素时可能导致的不确定性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、在Java中List.remove方法有个bug
1.看第一个针对Object的

boolean remove(Object var1);

看一下API接口,在看一下实现类
这里写图片描述
实现类:

/**
     * {@inheritDoc}
     *
     * <p>This implementation iterates over the collection looking for the
     * specified element.  If it finds the element, it removes the element
     * from the collection using the iterator's remove method.
     *
     * <p>Note that this implementation throws an
     * <tt>UnsupportedOperationException</tt> if the iterator returned by this
     * collection's iterator method does not implement the <tt>remove</tt>
     * method and this collection contains the specified object.
     *
     * @throws UnsupportedOperationException {@inheritDoc}
     * @throws ClassCastException            {@inheritDoc}
     * @throws NullPointerException          {@inheritDoc}
     */
    public boolean remove(Object o) {
        Iterator<E> it = iterator();
        if (o==null) {
            while (it.hasNext()) {
                if (it.next()==null) {
                    it.remove();
                    return true;
                }
            }
        } else {
            while (it.hasNext()) {
                if (o.equals(it.next())) {
                    it.remove();
                    return true;
                }
            }
        }
        return false;
    }

2.看第二个针对索引

E remove(int var1);

这里写图片描述
看一下实现类

/**
     * {@inheritDoc}
     *
     * <p>This implementation always throws an
     * {@code UnsupportedOperationException}.
     *
     * @throws UnsupportedOperationException {@inheritDoc}
     * @throws IndexOutOfBoundsException     {@inheritDoc}
     */
    public E remove(int index) {
        throw new UnsupportedOperationException();
    }

二、在实际工作中可能会出现的bug
看一下代码

package net.println.kotlin.chapter4;

import java.util.ArrayList;
import java.util.List;

/**
 * @author:wangdong
 * @description:看一下list的bug
 */
public class Bug {
    public static void main(String[] args) {
        List<Integer> integerList = new ArrayList<>();
        integerList.add(23);
        integerList.add(233);
        integerList.add(243);
        integerList.add(235);
        integerList.add(5);
        integerList.add(50);
        integerList.add(500);

        System.out.println(integerList);
        //这里会出现一个bug,当list中存在与索引相同的元素的时候,使用remove,就不知道会删除掉那个了
        integerList.remove(1);
        //这个5的索引是4,这样写可能就删除了索引为5的50,也可能是删除了5的元素
        integerList.remove(5);
        System.out.println(integerList);

    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值