美文网首页
LinkedList.remove()

LinkedList.remove()

作者: sgy_j | 来源:发表于2020-03-13 13:59 被阅读0次
LinkedList<Integer> list = new LinkedList<>();
list.add(1);
list.add(2);
list.remove(1);
System.out.println(list);

上面这段代码执行后,控制台输出结果会是什么呢?

先来看下JDK源码,从源码中我们找到有两个remove()方法,remove(int index) 和remove(Object o)。由于发生重载时,不会触发自动拆箱与自动装箱,所以上述代码调用了remove(int index)方法,上述代码输出结果为[1]

    public E remove(int index) {
        checkElementIndex(index);
        return unlink(node(index));
    }
    public boolean remove(Object o) {
        if (o == null) {
            for (Node<E> x = first; x != null; x = x.next) {
                if (x.item == null) {
                    unlink(x);
                    return true;
                }
            }
        } else {
            for (Node<E> x = first; x != null; x = x.next) {
                if (o.equals(x.item)) {
                    unlink(x);
                    return true;
                }
            }
        }
        return false;
    }

通过如下代码即可直接删除1这个元素。控制台输出结果[2]

LinkedList<Integer> list = new LinkedList<>();
list.add(1);
list.add(2);
list.remove(new Integer(1));
System.out.println(list);

综上所述,使用remove()方法时,要注意传入的参数类型!!
若想通过index删除元素,指定参数类型为int。
若想通过元素值删除元素,指定参数类型为Object。

相关文章

  • List系列->02LinkedList

    List层级关系: List系列: 一、LinkedList.add: 二、LinkedList.remove: ...

  • LinkedList.remove()

    上面这段代码执行后,控制台输出结果会是什么呢? 先来看下JDK源码,从源码中我们找到有两个remove()方法,r...

网友评论

      本文标题:LinkedList.remove()

      本文链接:https://www.haomeiwen.com/subject/ivzcshtx.html