removing special element from an arrayList
Hi I have written this part of code .before the for loop I have this arra开发者_开发知识库ylist :
[X :49.0 Y: 113.0 , angle :0.0, X :141.0 Y: 106.0 , angle :0.0, X :110.0 Y: 185.0 , angle: 1.0768211289482128, X :99.0 Y: 139.0 , angle: 1.9961041242180873, X :103.0 Y: 126.0 , angle : 2.4208694638343324]
which show "x" and "y" and "angle"
of some points.
but in the for loop I want to remove those elements that are more than
X :110.0 Y: 185.0 , angle: 1.0768211289482128
BUT it print this array for me :
[X :49.0 Y: 113.0angle0.0, X :141.0 Y: 106.0 , angle:0.0, X :110.0 Y: 185.0 , angle: 1.0768211289482128, X :103.0 Y: 126.0 , angle: 2.4208694638343324]
which is incorrect
int size = list .size();
for (int i=0;i<size;i++) {
if (list.get(i).getAngle() > pivot.getAngle() ) {
list.remove(i);
size--;
}
}
please help me thanks
Whenever you remove an element it shifts the indices of the following elements down by 1. The simplest fix is to go in reverse:
for (int i = list.size() - 1; i >= 0; i--) {
if (list.get(i).getAngle() > pivot.getAngle() ) {
list.remove(i);
}
}
I recommend you to get an Iterator
from the list
and use iter.hasNext()
, iter.next()
and iter.remove()
, like this:
Iterator<Point> iter = list.iterator();
while (iter.hasNext())
if (iter.next().getAngle() > pivot.getAngle())
iter.remove();
Another option would be to put them in a SortedMap
, let the angles represent the keys, and use tailMap(pivot.getAngle())
to get those points with a larger angle than the pivot.
When you remove the element, you should also lower your index value (i
) as otherwise it will skip the next value - because the values will have shifted. For example, imagine you originally had values { a, b, c, d, e }
. On the iteration where i==2
, you'd look at c
. If you then remove c
you're left with { a, b, d, e }
... when i
is incremented to 3 in the iteration part of the for
statement, that means list.get(i)
would return e
- so you'd never look at d
.
You can fix this by adding an i--;
statement inside your if
block... but a simpler approach is to work backwards from the end:
for (int i = list.size() - 1; i >= 0; i--) {
if (list.get(i).getAngle() > pivot.getAngle()) {
list.remove(i);
}
}
Alternatively, you might want to consider creating a new list which only contains the elements you do want to keep:
List<Foo> validValues = new ArrayList<Foo>();
for (Foo foo : list) {
if (foo.getAngle() <= pivot.getAngle()) {
validValues.add(foo);
}
}
精彩评论