嗨,我已经写了这个代码,输出你可以得到该.remove()方法不起作用.a,b,c,和d一些Points对象有x和y成员.
以下是a and b and c and d值,必须删除if语句中的值,upper但不是.
X :59 Y: 143
X :165 Y: 140
X :59 Y: 143
X :165 Y: 140
System.out.println(upper.toString());
for(int i =0;i<upper.size();i++)
if(upper.get(i)==a||upper.get(i)==b||upper.get(i)==c||upper.get(i)==d){
upper.remove(i);
}
for(int i =0;i<lower.size();i++)
if(lower.get(i)==a||lower.get(i)==b||lower.get(i)==c||lower.get(i)==d){
upper.remove(i);
}
System.out.println(upper.toString());
System.out.println(lower.toString());
first println : [X :108 Y: 89, X :165 Y: 140]
second println: [X :108 Y: 89, X :165 Y: 140]
third println : [X :105 Y: 191]
Run Code Online (Sandbox Code Playgroud)
如果我正确地阅读你的问题,那么你假设它==会比较两个对象的属性.它没有,那是什么equals.==告诉您两个引用是否属于同一个对象实例,而不是相同的对象实例.
例如:
public class Foo {
public Foo(int x, int y) {
this.x = x;
this.y = y;
}
@override
public boolean equals(Object other) {
Foo otherFoo;
if (other == null || !(other instanceof Foo)) { // or you might be more restrictive
return false;
}
otherFoo = (Foo)other);
return otherFoo.x == this.x && otherFoo.y == this.y;
}
@override
public int hashCode() {
// ...appropriate implementation of hashCode...
}
}
Foo a = new Foo(0, 0);
Foo b = new Foo(0, 0);
System.out.println(a == b); // "false"
System.out.println(a.equals(b)); // "true"
Run Code Online (Sandbox Code Playgroud)
另外:考虑当你必须ArrayList删除两个相关的匹配对象时会发生什么.假设他们在列表中的索引8和9处.所以,当i == 8你删除索引处的项目时8,以及之前的那个项目9现在处于8.但是然后你i在for循环中增加并继续使用索引处的新项目9,而保持第二个不变.如果要在循环中修改列表,请考虑向后循环以避免该列表,或使用Iterator.