Iterator<Player> iter = partyMembers.listIterator();
|
EDIT: solved.
The situation I have is that theres bunch of methods which need to loop through the partyMembers arraylist and those methods can add and remove from the list, and its possible to have multiple events happening in the same time, and because of that there might be 2 methods looping through the list at once, and if theres anything to add or remove from the list, it will end up with exception... is there something I could do to make it work as intended?
Heres an example method:
Code:public ArrayList<Player> partyMembers = new ArrayList<Player>(); public void exampleMethod(){ Iterator<Player> iter = partyMembers.iterator(); while (iter.hasNext()) { Player member = iter.next(); if (membersToRemove.contains(member)){ iter.remove(); continue; } member.actionSender.sendMessage("This was an example method."); } }
you what?
Edit: nvm I'm drunk, thought you just referred the normal iterator. Yeah, listiterator will probably work too here.
Seems like the only way to do what you're doing would be with a CopyOnWriteArrayList.
It's not very efficient though, if you use the collection heavily, might want to reconsider your structure of the code.
As name states, it creates a new underlying arraylist every time a mutation operation is performed on the list. So if you heavily modify the contents, it might not be a good idea, especially if the collection is large.
However the main benefit from using it is that it will never throw a concurrent modification exception, it is completely safe when it comes to that; if at all possible though, I'd avoid it; lots of unnecessary heap can cause gc to mess with your servers performance by causing spikes.
Another solution would be to maintain a collection of Player objects that need to be removed and added instead of removing them directly.
Code:Collection<Player> remove = new HashSet<>(); Collection<Player> add = new HashSet<>(); void onSomeGameTick() { for (Player member : partyMembers) { // if member should be removed, add to #remove collection // if member should be added, add to #add collection } partyMembers.addAll(add); partyMembers.removeAll(remove); }
« Previous Thread | Next Thread » |
Thread Information |
Users Browsing this ThreadThere are currently 1 users browsing this thread. (0 members and 1 guests) |