java - 从 TreeSet 中删除一个对象

标签 java collections treeset

所以我有以下相关代码:

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/

相关文章:

java - 当整个学生对象是唯一的时,为什么 TreeSet 不能让学生年龄相似?

java - 使用 TreeSet Java 计算反转

java - Java 新手请help.form n servlet

java - LinkedHashMap 是如何工作的?

java - 有没有一种优雅的方法可以将 map 流减少到一张 map

java - 计算 ArrayList 中特定变量的出现次数

php - Laravel 按类别对用户实体进行分组

java - 将 TreeSet 元素的顺序更改为自定义输出

java - 在枚举for循环中,它总是从第一个开始吗?

java - 当方向改变时,如何在 GridView 中保存位图图像的状态?