所以我有以下相关代码:
public static TreeSet<Object> set;
public static void remove(Object object){
for (Object o : set){
if (o.equals(object)){
System.out.println("removing " + o);
set.remove(o);
}
}
}
我向那个 TreeSet 添加了一些对象,然后我用某个 object1 作为参数调用 remove。 object1 在集合中,如
removingobject1
打印出来。
然而,当我之后使用这样的 for 循环打印出整个集合时:
for (Object o: set){
System.out.println(o);
}
它仍然打印出包括 object1 在内的整个集合。它显然在之前的集合中,Java 能够识别它,但是调用 set.remove(o) 绝对没有结果。
编辑:我试图让问题尽可能笼统,但这里是我正在使用的对象:
public class Player implements Comparable<Player>{
public String firstname;
public String lastname;
public int value;
public Position position;
public Player(String firstname, String lastname, int value, Position position){
this.firstname = firstname;
this.lastname = lastname;
this.value = value;
this.position = position;
}
public String toString(){
return(firstname + " " + lastname")
}
public int compareTo(Player player){
if (this.value > player.value){
return -1;
} else {
return 1;
}
}
最佳答案
您的删除方法可能如下所示:
public static void remove(Object object){
set.remove(o);
}
方法 remove 删除集合中存在的元素,如果删除则返回 true。您不应在迭代期间修改您的集合 ( docs ):
The iterators returned by this class's iterator method are fail-fast: if the set is modified at any time after the iterator is created, in any way except through the iterator's own remove method, the iterator will throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.
关于java - 从 TreeSet 中删除一个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42632118/