Note that there are some explanatory texts on larger screens.

plurals
  1. POUpdating a PriorityQueue when iterating it
    primarykey
    data
    text
    <p>I need to update some fixed-priority elements in a PriorityQueue based on their ID. I think it's quite a common scenario, here's an example snippet (Android 2.2):</p> <pre><code>for (Entry e : mEntries) { if (e.getId().equals(someId)) { e.setData(newData); } } </code></pre> <p>I've then made Entry "immutable" (no setter methods) so that a new Entry instance is created and returned by setData(). I modified my method into this:</p> <pre><code>for (Entry e : mEntries) { if (e.getId().equals(someId)) { Entry newEntry = e.setData(newData); mEntries.remove(e); mEntries.add(newEntry); } } </code></pre> <p>The code seems to work fine, but someone pointed out that modifying a queue while iterating over it is a bad idea: it may throw a ConcurrentModificationException and I'd need to add the elements I want to remove to an ArrayList and remove it later. He didn't explain why, and it looks quite an overhead to me, but I couldn't find any specific explanation on internet.</p> <p>(<a href="https://stackoverflow.com/questions/1871253/self-updating-java-priorityqueue">This post</a> is similar, but there priorities can change, which is not my case)</p> <p>Can anyone clarify what's wrong with my code, how should I change it and - most of all - why?</p> <p>Thanks, Rippel</p> <hr> <p>PS: Some implementation details...</p> <pre><code>PriorityQueue&lt;Entry&gt; mEntries = new PriorityQueue&lt;Entry&gt;(1, Entry.EntryComparator()); </code></pre> <p>with:</p> <pre><code>public static class EntryComparator implements Comparator&lt;Entry&gt; { public int compare(Entry my, Entry their) { if (my.mPriority &lt; their.mPriority) { return 1; } else if (my.mPriority &gt; their.mPriority) { return -1; } return 0; } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload