ConcurrentModificationException when using PriorityQueue

I use a for loop for each loop to iterate over PriorityQueueand try to poll it.

Why am I getting java.util.ConcurrentModificationException? Where can I change the " concurrently" as implied in the exception name? Is the assignment itself a modification since it internally uses poll ()? Explain, please.

Excerpt:

String[] sa = {">ff<", "> f<", ">f <", ">FF<"};
        //This code demonstrates that white spaces come before capital letters and 
        //capital letters come before the small letters in natural ordering
        PriorityQueue<String> pq = new PriorityQueue<String>();
        for (String str : sa) {
            pq.offer(str);
        }
        System.out.println(pq);
        for (String str : pq) {
            System.out.print(pq.poll() + " ");
        }
}

Edit:

As I understand from the explanations below, each call to the poll () method causes a resize of the object PriorityQueue. Thus, it makes sense to throw an exception when repeating and trying to poll ( varying the size constantly). Therefore, the object pqthrows an exception that is incorrect. Do I understand correctly?

+4
5

java.util.ConcurrentModificationException?.

.

"", ?

, poll(). ( )... .

, poll()?

(String str: pq). pq str ?

. poll .

! for , hasNext() next(). . poll , . ( / PriorityQueue.)


, ( ) , Iterator, Collection. "" for , Iterator.

@Shekhar Iterator, CME.

, , - Iterator?

, Java ! Java " " . - JLS 14.14.2.

( , "" for .)

+3

(pq.poll()) (for (String str : pq)).

, , concurrency . " ". , , β€” -β€” ConcurrentModificationException. , ; , , , . , PriorityQueue, .

+4

, :

while (!pq.isEmpty()) {
        System.out.print(pq.poll() + " ");
    }

ConcurrentModificationException.

+3

ConcurrentModificationException javadocs

, , . , , . , , , .

+1

CME , " (, ) . poll(), , PriorityQueue.java poll()"

, Iterator . CME

+1
source

Source: https://habr.com/ru/post/1535140/


All Articles