使用iterator删除list,map中元素

使用iterator删除list,map元素

  • 答案优先
  • 解析Iterator of List
  • 解析Iterator of Map

Answer

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

        list.add("1");
        list.add("2");
        list.add("3");

        Iterator<String> listIt = list.iterator();

        while(listIt.hasNext())
        {
            listIt.next(); //.next() 需要被调(无论是否需要检查此值),否则报java.lang.IllegalStateException
            listIt.remove();
        }
        Map<String, String> map = new HashMap<>();

        map.put("attr1", "1");
        map.put("attr2", "2");
        map.put("attr3", "3");

        Iterator mi = map.keySet().iterator();

        while(mi.hasNext()){

            mi.next();//.next() 需要被调用,否则报java.lang.IllegalStateException
            mi.remove();

        }

解析Iterator of List

以ArrayList类为例,它包含了一个内部类:ArrayList$Itr.class ,其中包含三个int数值

int cursor; // 下个返回元素
int lastRet = -1; // 上个返回元素(remove问题出在此)
int expectedModCount = modCount; //容器大小
调用iterator的remove方法时,要提前调下.next()

public void remove() {
    if (lastRet < 0)
        throw new IllegalStateException(); //@1
    checkForComodification();

    try {
        ArrayList.this.remove(lastRet);
        cursor = lastRet;
        lastRet = -1; //@2
        expectedModCount = modCount;
    } catch (IndexOutOfBoundsException ex) {
        throw new ConcurrentModificationException();
    }
}

@1: 此处每次调用remove()时都会判断lastRet的值
@2: 成功remove后,重置-1,结果就导致下次remove前,如果lastRet值未被改变,异常依旧

然而lastRet值只能被.next()方法修改@3:

public E next() {
    checkForComodification();
    int i = cursor;
    if (i >= size)
        throw new NoSuchElementException();
    Object[] elementData = ArrayList.this.elementData;
    if (i >= elementData.length)
        throw new ConcurrentModificationException();
    cursor = i + 1;
    return (E) elementData[lastRet = i]; //@3 lastRet修改在此,源码里就只在这可以被设置成>0的值
}

解析Iterator of Map

HashMap

    Node<K,V> next;        // 下个返回Entry
    Node<K,V> current;     // 当前Entry
    int expectedModCount;  // 
    int index;             // 当前位置

    HashIterator() {
        expectedModCount = modCount; //初始化到当前map大小
        Node<K,V>[] t = table;
        current = next = null; //current初始值null
        index = 0;
        if (t != null && size > 0) { // advance to first entry
        do {} while (index < t.length && (next = t[index++]) == null);
        }
    }
public final void remove() {
    Node<K,V> p = current;
    if (p == null) //然而这里会判断当前entry的值,与list类似,也只有在调用HashIterator.nextNode()时
                   //才会更新current到新的node上,所以在remove()前调用Iterator.next()在Map也是必要的
        throw new IllegalStateException();
    if (modCount != expectedModCount)
        throw new ConcurrentModificationException();
    current = null;
    K key = p.key;
    removeNode(hash(key), key, null, false, false);
    expectedModCount = modCount;
}

LinkedHashMap & LinkedList

这两个容器与基础的HashMap和ArrayList有所区别

private Node<E> lastReturned;

LinkedList中,可以改变lastReturned值得方法也只有内部类中的ListItr中的next(),因为双向链表维护的对象,因此多了previous()和forEachRemaining()方法。

在另一个map容器IdentityHashMap的内部类IdentityHashMapIterator里也存在:
int lastReturnedIndex = -1;

在IdentityHashMap的内部类EntryIterator中:

public void remove() {
    lastReturnedIndex =
    ((null == lastReturnedEntry) ? -1 : lastReturnedEntry.index); //@4
    super.remove();
    lastReturnedEntry.index = lastReturnedIndex;
    lastReturnedEntry = null;
}

@4:lastReturnedEntry在初始化时也是指向了‘当前’的那个entry,从而保证了iterator的游标是在向后移动的

总结

‘保证了iterator的游标是在向后移动的’这个结论是推测的,以上无论是ArrayList的lastRet,和linkedhashmap的lastReturnedIndex,包括hashmap和linkedlist中对于当前node

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值