ArrayList与LinkedList移除指定元素对比(源码分析)

简介: ArrayList与LinkedList移除指定元素对比(源码分析)

ArrayList移除元素

首先在主函数中调用ArrayList的有参构造方法生成一个List实例list,并且发现共有四种移除元素的方法:

List<String> list = new ArrayList<>(Arrays.asList("A", "B", "C", "D", "E", "F", "G", "H", "I", "J"));
list.remove(3);
list.remove("H");
list.removeAll(Arrays.asList("F", "G"));
list.clear();


remove(int index)

点进去第一个remove方法:

/**
 * Removes the element at the specified position in this list.
 * Shifts any subsequent elements to the left (subtracts one from their
 * indices).
 *
 * @param index the index of the element to be removed
 * @return the element that was removed from the list
 * @throws IndexOutOfBoundsException {@inheritDoc}
 */
public E remove(int index) {
    rangeCheck(index);
    modCount++;
    E oldValue = elementData(index);
    int numMoved = size - index - 1;
    if (numMoved > 0)
        System.arraycopy(elementData, index+1, elementData, index,
                         numMoved);
    elementData[--size] = null; // clear to let GC do its work
    return oldValue;
}


首先检验index是否合法,然后将index对应元素赋值给oldValue,需要移动的元素为index之后的所有元素,总数为size-index-1,使用System.arraycopy来将index之后的所有元素向前移动一位;该方法时间复杂度较高;


remove(Object o)

点进去第二个remove方法:

/**
 * Removes the first occurrence of the specified element from this list,
 * if it is present.  If the list does not contain the element, it is
 * unchanged.  More formally, removes the element with the lowest index
 * <tt>i</tt> such that
 * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>
 * (if such an element exists).  Returns <tt>true</tt> if this list
 * contained the specified element (or equivalently, if this list
 * changed as a result of the call).
 *
 * @param o element to be removed from this list, if present
 * @return <tt>true</tt> if this list contained the specified element
 */
public boolean remove(Object o) {
    if (o == null) {
        for (int index = 0; index < size; index++)
            if (elementData[index] == null) {
                fastRemove(index);
                return true;
            }
    } else {
        for (int index = 0; index < size; index++)
            if (o.equals(elementData[index])) {
                fastRemove(index);
                return true;
            }
    }
    return false;
}

使用遍历的方式去寻找该对象,发现第一个与该对象相等的元素,使用fastRemove方法进行移除,并返回true,因此该方法只能移除第一个与该对象相等的元素。点进去fastRemove方法:

/*
 * Private remove method that skips bounds checking and does not
 * return the value removed.
 */
private void fastRemove(int index) {
    modCount++;
    int numMoved = size - index - 1;
    if (numMoved > 0)
        System.arraycopy(elementData, index+1, elementData, index,
                         numMoved);
    elementData[--size] = null; // clear to let GC do its work
}


发现该方法也是通过System.arraycopy将index之后的所有元素向前移动一位;该方法时间复杂度较高;

removeAll(Collection<?> c)

点进去removeAll方法

/**
 * Removes from this list all of its elements that are contained in the
 * specified collection.
 *
 * @param c collection containing elements to be removed from this list
 * @return {@code true} if this list changed as a result of the call
 * @throws ClassCastException if the class of an element of this list
 *         is incompatible with the specified collection
 * (<a href="Collection.html#optional-restrictions">optional</a>)
 * @throws NullPointerException if this list contains a null element and the
 *         specified collection does not permit null elements
 * (<a href="Collection.html#optional-restrictions">optional</a>),
 *         or if the specified collection is null
 * @see Collection#contains(Object)
 */
public boolean removeAll(Collection<?> c) {
    Objects.requireNonNull(c);
    return batchRemove(c, false);
}


首先对集合c转进行NonNull校验,然后使用batchRemove方法进行移除;点进去batchRemove:

private boolean batchRemove(Collection<?> c, boolean complement) {
    final Object[] elementData = this.elementData;
    int r = 0, w = 0;
    boolean modified = false;
    try {
        for (; r < size; r++)
            if (c.contains(elementData[r]) == complement)
                elementData[w++] = elementData[r];
    } finally {
        // Preserve behavioral compatibility with AbstractCollection,
        // even if c.contains() throws.
        if (r != size) {
            System.arraycopy(elementData, r,
                             elementData, w,
                             size - r);
            w += size - r;
        }
        if (w != size) {
            // clear to let GC do its work
            for (int i = w; i < size; i++)
                elementData[i] = null;
            modCount += size - w;
            size = w;
            modified = true;
        }
    }
    return modified;
}


本质上是将elementData进行一次遍历,将集合c中不包含的元素依次重新放入elementData即可,然后将最后数量为c的size的元素置为null;也涉及到元素的移动,不过只需一次遍历即可;

clear()

点进去clear方法

/**
 * Removes all of the elements from this list.  The list will
 * be empty after this call returns.
 */
public void clear() {
    modCount++;
    // clear to let GC do its work
    for (int i = 0; i < size; i++)
        elementData[i] = null;
    size = 0;
}


将所有元素置为null即可;

LinkedList移除元素

首先在主函数中调用LinkedList的有参构造方法生成一个List实例list(若生成LinkedList实例,则有更多关于队列操作的方法,但在这里我们只对比LinkedList与ArrayList在List上的区别),并且发现共有四种移除元素的方法:

List<String> list = new LinkedList<>(Arrays.asList("A", "B", "C", "D", "E", "F", "G", "H", "I", "J"));
list.remove(3);
list.remove("H");
list.removeAll(Arrays.asList("F", "G"));
list.clear();


remove(int index)

点进去第一个remove方法:

/**
 * Removes the element at the specified position in this list.  Shifts any
 * subsequent elements to the left (subtracts one from their indices).
 * Returns the element that was removed from the list.
 *
 * @param index the index of the element to be removed
 * @return the element previously at the specified position
 * @throws IndexOutOfBoundsException {@inheritDoc}
 */
public E remove(int index) {
    checkElementIndex(index);
    return unlink(node(index));
}


首先检验index是否合法,然后使用unlink方法来移除元素。点进去unlink:

/**
 * Unlinks non-null node x.
 */
E unlink(Node<E> x) {
    // assert x != null;
    final E element = x.item;
    final Node<E> next = x.next;
    final Node<E> prev = x.prev;
    if (prev == null) {
        first = next;
    } else {
        prev.next = next;
        x.prev = null;
    }
    if (next == null) {
        last = prev;
    } else {
        next.prev = prev;
        x.next = null;
    }
    x.item = null;
    size--;
    modCount++;
    return element;
}


仅需使要被移除元素的prev.next直接指向被移除元素的next,使要被移除元素的next.prev直接指向被移除元素的prev即可,无需移动元素;

remove(Object o)

点进去第二个remove方法:

/**
 * Removes the first occurrence of the specified element from this list,
 * if it is present.  If this list does not contain the element, it is
 * unchanged.  More formally, removes the element with the lowest index
 * {@code i} such that
 * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>
 * (if such an element exists).  Returns {@code true} if this list
 * contained the specified element (or equivalently, if this list
 * changed as a result of the call).
 *
 * @param o element to be removed from this list, if present
 * @return {@code true} if this list contained the specified element
 */
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;
}


使用遍历的方式去寻找该对象,发现第一个与该对象相等的元素,使用unlink方法进行移除,并返回true,因此该方法只能移除第一个与该对象相等的元素。无需移动任何元素;

removeAll(Collection<?> c)

点进去removeAll方法

/**
 * {@inheritDoc}
 *
 * <p>This implementation iterates over this collection, checking each
 * element returned by the iterator in turn to see if it's contained
 * in the specified collection.  If it's so contained, it's removed from
 * this collection with the iterator's <tt>remove</tt> method.
 *
 * <p>Note that this implementation will throw an
 * <tt>UnsupportedOperationException</tt> if the iterator returned by the
 * <tt>iterator</tt> method does not implement the <tt>remove</tt> method
 * and this collection contains one or more elements in common with the
 * specified collection.
 *
 * @throws UnsupportedOperationException {@inheritDoc}
 * @throws ClassCastException            {@inheritDoc}
 * @throws NullPointerException          {@inheritDoc}
 *
 * @see #remove(Object)
 * @see #contains(Object)
 */
public boolean removeAll(Collection<?> c) {
    Objects.requireNonNull(c);
    boolean modified = false;
    Iterator<?> it = iterator();
    while (it.hasNext()) {
        if (c.contains(it.next())) {
            it.remove();
            modified = true;
        }
    }
    return modified;
}


首先对集合c转进行NonNull校验,然后使用Iterator进行遍历,移除所有集合c包含的元素;无需对元素进行移动;

clear()

点进去clear方法

/**
 * Removes all of the elements from this list.
 * The list will be empty after this call returns.
 */
public void clear() {
    // Clearing all of the links between nodes is "unnecessary", but:
    // - helps a generational GC if the discarded nodes inhabit
    //   more than one generation
    // - is sure to free memory even if there is a reachable Iterator
    for (Node<E> x = first; x != null; ) {
        Node<E> next = x.next;
        x.item = null;
        x.next = null;
        x.prev = null;
        x = next;
    }
    first = last = null;
    size = 0;
    modCount++;
}


遍历将所有元素以及元素的prev和next置为null即可;

结论

1.ArrayList应尽量避免移除元素操作,因为移除元素需要复制移动一次被移除元素之后的数据,所需时间较长;

2.如ArrayList无法避免移除元素操作,应尽量将多个要移除的元素形成一个集合,使用removeAll(Collection<?> c)方法进行移除,因为只会移动一次数据,可以少花费时间;

3.对于需要经常移除元素的场景,应尽量使用LinkedList来实现,所需时间复杂度较低;

目录
相关文章
|
3月前
|
人工智能 机器人 数据挖掘
WhatsApp API最新收费调整:Meta Business Agent按Token收费,Service消息10月起按条计费
2026年8月起,Meta Business Agent按Token收费;10月起,24小时窗口内的Service消息和Utility模板正式按条计费。WhatsApp客服回复、AI应答和订单通知不再免费。本文详解规则变化、成本影响及企业降本策略。
457 3
|
5月前
|
存储 API 数据库
RAG检索增强怎么搭建:从原理到落地的完整路径
RAG(检索增强生成)通过“先检索、再生成”机制,将外部知识库与大模型结合,解决幻觉、数据过时及私有数据不可用问题。涵盖文档解析、文本分块、向量化存储、检索生成四大环节,强调分块策略、检索质量与提示词约束的协同优化。(239字)
|
4月前
|
人工智能 安全 UED
刚刚,阿里悄悄上线了他们最新视频模型:Wan3.0【附10种神仙玩法】
1080P 30秒视频!打骨折价,AI视频终于卷起来啦~
851 0
|
弹性计算 运维 安全
2025年选购指南:阿里云轻量应用服务器与云服务器ECS深度对比
阿里云轻量应用服务器与ECS区别解析:轻量适合个人开发者搭建博客、测试环境,配置简单、成本低,68元/年起;ECS适用于企业级高负载场景,如大数据、游戏等,功能全面但门槛较高。根据使用需求选择更优。
939 6
|
6月前
|
弹性计算 运维 关系型数据库
阿里云CLI与批处理集成:云运维提效的5个实战技巧
在阿里云环境中,运维工程师每天面对大量重复性操作——批量ECS巡检、OSS文件同步、RDS备份管理、安全组规则维护等任务占用大量时间。本文分享5个基于阿里云CLI和批处理集成的实战技巧,通过aliyun-cli命令行工具、ossutil对象存储工具、RAM权限管理和自动化脚本框架,将云运维效率提升70%以上。以每月100台ECS实例的运维规模计算,年节省运维成本超过10万元。
|
6月前
|
数据采集 前端开发 JavaScript
别只盯着HTML了!教你高效抓取并解析PDF/Excel隐藏附件?
本文聚焦网页附件(PDF/Excel)爬取痛点,系统讲解隐藏链接识别、二进制文件下载、pdfplumber/pandas精准解析及代理IP轮换反爬策略,并附完整实战代码,助你高效获取高价值结构化数据。(239字)
788 0
|
6月前
|
人工智能 自然语言处理 供应链
做跨境代购 APP,用好这几个技巧就够了
跨境代购仍有机会,但已从“信息差”转向“系统化运营”。taocarts系统助力效率提升3-5倍、成本降40%-50%,支持自动采购、多语言、实时汇率、物流追踪与私域运营,赋能OPC(一人跨境)新模式。
378 1
|
存储 Java 开发者
在 Java 中,如何遍历一个 Set 集合?
【10月更文挑战第30天】开发者可以根据具体的需求和代码风格选择合适的遍历方式。增强for循环简洁直观,适用于大多数简单的遍历场景;迭代器则更加灵活,可在遍历过程中进行更多复杂的操作;而Lambda表达式和`forEach`方法则提供了一种更简洁的函数式编程风格的遍历方式。
5024 113
|
SQL 分布式计算 数据挖掘
从Excel到高级工具:数据分析进阶指南
从Excel到高级工具:数据分析进阶指南
807 54