簡體   English   中英

使用Iterator時出現ConcurrentModificationException

[英]ConcurrentModificationException when using Iterator

我正在嘗試使用Iterator迭代一個ArrayList。 問題是我得到了ConcurrentModificationException 我檢查了很多像這樣的問題。 所有人都說當你在迭代它時修改一個ArrayList時會發生異常。 但我認為我的問題有點不同,因為即使使用Iterator方法我也不會修改ArrayList

        Cliente cliente1 = new Cliente(16096,"Alberto1","pass",1500.0,false);

    ArrayList<Cliente> miLista = new ArrayList<Cliente>();

    Iterator<Cliente> miIterador = miLista.iterator();

    miLista.add(cliente1);

    System.out.println(miLista.get(0).nombre); //This displays "Alberto1"
    System.out.println(miIterador.hasNext()); //This displays 'true'
    miIterador.next(); //Here I get the exception

我不知道如何解決它。 這可能是一個愚蠢的問題,因為實際上我是初學者,但我被困在這里。

謝謝。

- 甚至不能回答我自己的問題,所以我用答案編輯問題:

非常感謝你們所有人! 你們都給了我正確的答案:D對不起那個愚蠢的問題:P

解決了

這條線是罪魁禍首。 除非通過迭代器自己的remove或add方法,否則在以任何方式獲取迭代器之后都無法修改列表。

miLista.add(cliente1);

ArrayList類的iterator和listIterator方法返回的迭代器是快速失敗的:如果在創建迭代器之后的任何時候對列表進行結構修改,除了通過迭代器自己的remove或add方法之外,迭代器將拋出ConcurrentModificationException

“但我認為我的問題有點不同,因為即使使用Iterator方法我也沒有修改ArrayList。”

但是你是通過添加一個元素修改列表:)

    ArrayList<Cliente> miLista = new ArrayList<Cliente>();

    Iterator<Cliente> miIterador = miLista.iterator();

    miLista.add(cliente1); 
    ^^^^^^^^^^^^^^^^^^^^^^ here!

這是有問題的一行,你通過添加對象來制作arraylist。 Iterator是在真正的數組列表上進行的,因此它會以異常快速的方式拋出異常。

miLista.add(cliente1);

這是來自arrayList類的一段代碼,它在迭代器上調用getNext時會被觸發。

 final void checkForComodification() {
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
        }

生成Iterator 后,您正在修改列表。 只需交換線路

Iterator<Cliente> miIterador = miLista.iterator();

miLista.add(cliente1);

一切都會好起來的。

另一種方法是使用ListIterator,並在插入新客戶端后回退迭代器

    Cliente cliente1 = new Cliente(16096,"Alberto1","pass",1500.0,false);

    ArrayList<Cliente> miLista = new ArrayList<Cliente>();

    ListIterator<Cliente> miIterador = miLista.listIterator();

    miIterador.add(cliente1);
    miIterador.previous();

    System.out.println(miLista.get(0).getHombre()); //This displays "Alberto1" << notice you're not using the iterator here
    System.out.println(miIterador.hasNext()); //This displays 'true'
    System.out.println(miIterador.next().getHombre()); //This displays "Albert1" again

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM