Reputation: 15661
How to remove specific element on List?
...
java.util.List<Polygon> triangles = new LinkedList<Polygon>();
Point startDrag, endDrag, midPoint;
Polygon triangle;
....
int[] xs = { startDrag.x, endDrag.x, midPoint.x };
int[] ys = { startDrag.y, startDrag.y, midPoint.y };
triangles.add( new Polygon(xs, ys,3));
....
public void mouseClicked(MouseEvent e) {
...
startDrag = new Point(e.getX(), e.getY());
for (Polygon p:triangles){
if (p.contains(startDrag)) //Polygon has a 'contains(Point)' method
remove (p.contains(startDrag));
}
....
Upvotes: 1
Views: 7289
Reputation: 656
This is a nasty, I dug it - it's the system thread from the Mouse Clicked being identified as not the creator of the java.util.Thingamabob ( a new data structure to be released tomorrow )
Despite documentation, in alignment with common sense, what the thing does actually is see that the thread from MouseClicked is not the Thread that created
java.util.List<Polygon> triangles
using something on the order of Thread ID or such as naming of threads go and then throws from deep within the JVM an exception ( sets the exception flag on the C side ) then returns leaving you with no functioning exception.getMessage() .....
You can implement copy semantics and the original version will work, does some bit-twisting on your brain but it works.
Upvotes: 0
Reputation: 7061
To remove by object, such as removing a specific triangle from a triangle list, use List::remove(Object)
For the above purposes, you might want to use List::listIterator(), though. Something like:
ListIterator<Polygon> it = triangles.listIterator();
while (it.hasNext()) {
if (it.next().contains(startDrag)) {
it.remove();
break;
}
}
Upvotes: 3
Reputation: 39485
You will not be able to remove the object from the triangles
list if you are currently iterating over it. If you try to do so, you will trigger a ConcurrentModificationException
. Instead, what you should do is make a copy of the list and iterate over that, and when you get a hit, remove the item from the original:
public void mouseClicked(MouseEvent e) {
...
Polygon[] triArray = triangles.toArray(new Polygon[triangles.size()]);
startDrag = new Point(e.getX(), e.getY());
for (Polygon p:triArray){
if (p.contains(startDrag)) //Polygon has a 'contains(Point)' method
triangles.remove (p);
}
....
Upvotes: 2