Java ArrayList.removeRange() 方法及代码示例

从当前数组列表中删除其索引介于 fromIndex(包含)和 toIndex(不包含)之间的所有元素

定义

protected void removeRange​(int fromIndex, int toIndex)

参数

参数类型参数名称参数描述
intfromIndex要移除的起始索引
inttoIndex要移除的结束索引

抛出的异常

IndexOutOfBoundsException - 如果 fromIndex 或 toIndex 超出范围 (fromIndex < 0 || toIndex > size() || toIndex < fromIndex)

说明

本方法方法由 AbstractList<E> 接口的 removeRange() 方法指派

removeRange()ArrayList 中的实现如下:

    protected void removeRange(int fromIndex, int toIndex) {
        if (fromIndex > toIndex) {
            throw new IndexOutOfBoundsException(
                    outOfBoundsMsg(fromIndex, toIndex));
        }
        modCount++;
        shiftTailOverGap(elementData, fromIndex, toIndex);
    }

AbstractList<E> 中的 clear() 调用了 removeRange() 方法, 但 clear() 方法在本类(即ArrayList类)中被重写了, 且  removeRange() 方法是声明为 protected 的. 因此示例中我们将自定义继承自ArrayList类的类, 通过 myClear() 方法来实现  AbstractList<E> 中的 clear() 方法.

注意事项

需要注意的是, ArrayList 与 AbstractList<E> 的具体实现不同, 示例中的 myClear() 方法的实现仅供参考, 无法替代 clear() 的真正实现.

示例

重写 removeRange() 的示例

package com.yi21.arraylist;

import java.util.ArrayList;

public class Yi21ArraysListRemoveRange {

    public static class MyArrayList<E> extends ArrayList<E> {

        public void myClear() {
            removeRange(0, size());
        }

    }

    public static void main(String[] args) {
        
        MyArrayList<String> list = new MyArrayList<>();
        list.add("Hello");
        list.add("World");
        list.add("World");
        list.add("21yi");
        list.myClear();
        System.out.println("数组列表剩余元素: " + list.size());
        
    }

}

执行结果为 :

数组列表剩余元素: 0