Im having problems with removing items from an arraylist using an iterator. My aim is to retrieve points within a certain radius and cluster them into a set of groups. I am using the initial points as a reference. The code has an initial for loop that will run through each place, then for each place an inner for loop is created to check the radius between the reference place and the rest of places. If the radius between both reference place and other place is less than a threshold i set, it will be added to the arraylist grouped with other similar points. As they are added to groups they will be removed from the original arraylist.
However i am getting problems such as it either only performs the outer for loop once or i get an IllegalStateException.
Here is the code:
HashMap<Place, ArrayList<Place>> sets = new HashMap<Place, ArrayList<Place>>();
private void cluster(ArrayList<Place> places) {
for (Iterator<Place> iterator = places.iterator(); iterator.hasNext();) {
Place pl = iterator.next();
ArrayList<Place> subset = new ArrayList<Place>(); // Group
GeoPoint g = new GeoPoint((int) (pl.getGeometry().getLocation()
.getLat() * 1e6), (int) (pl.getGeometry().getLocation()
.getLng() * 1e6));
Point point = new Point();
mapView.getProjection().toPixels(g, point);
sets.put(pl, subset);
subset.add(pl);
iterator.remove();
for (Iterator<Place> iterator2 = places.iterator(); iterator2
.hasNext();) {
Place pl2 = iterator2.next();
int threshold = 100;
GeoPoint g2 = new GeoPoint((int) (pl2.getGeometry()
.getLocation().getLat() * 1e6), (int) (pl2
.getGeometry().getLocation().getLng() * 1e6));
Point point2 = new Point();
mapView.getProjection().toPixels(g2, point);
int dx = Math.abs(point2.x - point.x);
int dy = Math.abs(point2.y - point.y);
if (dx < threshold && dy < threshold) {
subset.add(pl2);
iterator2.remove();
}
}
}
}
Sorry for the info overload, would really appreciate the help.
Thanks in advance peeps
Rehan
You are stepping the outer iterator inside the inner loop. It looks like these lines might be in error:
Looks like maybe you copied and pasted without changing the terminating condition in the loop and the following line: