Java 集合的remove()方法

首先,remove()方法有两种移除的方式:

1、根据下标移除

2、根据内容移除

原则是这样的

首先源码:

    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;
    }
    /**
     * 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 ? get(i)==null : 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;
    }

可以看出一个是可以传入index(int)下标的移除方式,另一个是Object类型的内容。当我们传入参数的时候,可以根据是下标还是内容对集合进行移除的操作。

但实际上有些操作并不能愉快实现。

ArrayList list = new ArrayList();

add(1);

add(4);

add(3);

如果想删除4那个数据,直接list.remove(4);运行程序会下标越界,原因是因为remove方法是一个被重载的方法,根据传入参数有int型(既下标索引)和Object(对象)型的两种方法,首先要知道直接输入一个整数如4,在没有声明变量类型的时候程序默认是int型,即使你在编译器里选用的是Object(对象)方法,程序运行时也是根据重载的机制以传入参数的类型而调用方法,因此list.remove(4)调用的是根据数组下标删除数据的方法,而非根据对象删除的方法,所以我们需要这样写:list.remove((Integer)4);这时4从int型被转为Integer型,程序运行时根据对象类型调用remove(Object)方法



集合是有顺序的,先add的编号就小(从0开始),这样就可以通过remove(编号)的形式进行删除,之后后面的会编号依次变小(也就是说编号总是连续的)。举例:
List list = new linkedList();
list.add("0");
list.add("1");
list.remove(0);
结果就是:list.get(0) =1;
备注:如果再一次“list.remove(0);”那么list对象就是个空。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值