java - Need help modifying list based on comparison values (ConcurrentModification) -
i trying see possibility there (don't tell me there isn't, failed project) throughout arrangement of points , distances.
for (point p1 : results) { remove.clear(); (point p2 : results) { if (math.sqrt( math.pow(p1.getx() - p2.getx(), 2) + math.pow(p1.gety() - p2.gety(), 2) ) % 1 > 0) { results.remove(p2); } } } basically, trying check if 2 points have integer distance, and, if not, remove set, , points (that remain).
however, getting concurrentmodificationexception , not how refactor accomplish same task without provoking error in way.
are there ways around or limitation of java?
edit: while duplicate suggested link offers insight, answers' focus on single loops has berth of excess not applicable. if question duplicate, it's on premise of using iterator answer.
some collection implementations use "fail-fast" iterator. when removing item collection directly (using collection#remove) while iterating on cause exception.
enhanced for-loops uses collection's iterator iterate through collection.
you change enhanced loops regular loops:
for(int = 0; < results.size(); i++) { for(int j = 0; j < results.size(); j++) { point result = results.get(j); if(...) { //results.remove(j); or //results.remove(result); } } } as mentioned in comments, not work set. in case, keep reference collection's iterator, , use remove item:
iterator<point> firstiter = results.iterator(); while(firstiter.hasnext()) { point p1 = iterator.next(); iterator<point> seconditer = results.iterator(); while(seconditer.hasnext()) { point p2 = seconditer.next(); if(...) { seconditer.remove(); } } }
Comments
Post a Comment