Java基础之集合移除元素(Iterator)

来源:互联网 发布:大学生淘宝兼职 编辑:程序博客网 时间:2024/06/17 08:34

题目:存在一个集合List,需要剔除其中的值为设定值“2”的对象,如何实现

 

一、题目A

List<String> list = new ArrayList<String>();

               list.add("1");

               list.add("2");

               list.add("3");

               list.add("4");

               list.add("5");

 

1.1 分析

这还用想么,直接循环元素如果value等于2删除不就好了

1.2 逻辑

for (int i =0; i < list.size(); i++) {

                       if(list.get(i).equals("2")) {

                               list.remove(i);

                       }

               }

               System.out.println("result" + list.toString());

也许有的人可能还会觉得这里会出现运行时异常,后面进行解释为什么不会

1.3 结果输出

result [1, 3, 4, 5]

 

 

二、题目B

List<String> list = new ArrayList<String>();

               list.add("1");

               list.add("2");

               list.add("2");// 重复2的情况

               list.add("3");

               list.add("4");

               list.add("5");

1.1 分析


这还用想么,肯定还是直接循环元素如果value等于2删除不就好了

1.2 逻辑

 

List<String> list = new ArrayList<String>();

                list.add("1");

               list.add("2");

               list.add("2");// 重复2的情况

               list.add("3");

               list.add("4");

               list.add("5");

 

 

1.3 结果输出


result [1, 2, 3, 4, 5]

呀,出bug了。。。我明明已经把为2的都进行删除了啊。

 

三、源码分析


直接上源码,若想知道这是为什么就需要看看ArrayList.remove(intidex)都干了写什么

1.1 源码

/**

     * Removes the element at the specifiedposition in this list.

     * Shifts any subsequentelements to the left (subtracts one from their

     * indices).

     *

     * @param index the index of theelement to be removed

     * @return the element that wasremoved from the list

     * @throwsIndexOutOfBoundsException {@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;// Let gc do its work

 

        return oldValue;

    }

 

/**

     * Checks if the given index isin range.  If not, throws an appropriate

     * runtime exception.  This method does *not* check if the index is

     * negative: It is always usedimmediately prior to an array access,

     * which throws anArrayIndexOutOfBoundsException if index is negative.

     */

    private void rangeCheck(intindex) {

        if (index >= size)

            throw newIndexOutOfBoundsException(outOfBoundsMsg(index));

    }

 

1.2 图解

 

1.3 总结

因此会出现现象:只移除了第一个2的问题。并且数组越界的判定为坐标是否大于等于list个数,因此并未出现运行时异常。

但是也并非所有集合如此,具体要看接口List的实现类对于remove方法的实现。

例如:假如目标题目改为如下还可以运行正常么?为什么?

List<String> list =Arrays.asList("1","2","3","4","5");

 

 

四、主人公Iterator

主人公要干活去了。。。

 

 

 

 

 

0 0
原创粉丝点击