您现在的位置是:首页 > 文章详情

Java中List.remove()方法的bug

日期:2018-04-01点击:487

一、在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);

    }
}
原文链接:https://yq.aliyun.com/articles/614573
关注公众号

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。

持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。

转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。

文章评论

共有0条评论来说两句吧...

文章二维码

扫描即可查看该文章

点击排行

推荐阅读

最新文章