4

So I have the following relevant code:

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);
        }
    }
}

I add a few objects to that TreeSet, then I call remove with a certain object1 as an argument. The object1 is in the set, as

removingobject1

is printed out.

Yet, when I then print out the whole set after that using a for-loop like this:

for (Object o: set){
        System.out.println(o);
    }

It still prints out the whole set including object1. It was clearly in the collection before, which Java was able to recognize, yet calling set.remove(o) results in absolutely nothing.

edit: I tried to keep the question as general as possible, but here are the objects that I'm using:

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;
    }
}
Lukas Tilmann
  • 73
  • 1
  • 5

1 Answers1

1

Your remove method could look like:

public static void remove(Object object){
   set.remove(o);
}

Method remove removes element if it is present in the set, and returns true if it was removed. You should not modify your set during the iteration (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.

Natalja Olefire
  • 442
  • 5
  • 9
  • This is true, but doesn't answer the question. And I suspect the iteration was just to prove the element is in the set. – shmosel Mar 06 '17 at 17:56
  • 1
    In this case then it should throw ConcurrentModificationException as one element is removed and the modCount value is changed so the iterator should fail. – Rahul Vedpathak Mar 06 '17 at 17:56
  • I have actually tried it this way and somehow it didn't work. I implemented the for loop to see if Java recognizes that the object is still in the set (which it is). If remove(o) actually worked naturally I'd delete the unnecessary for loop. ;) – Lukas Tilmann Mar 06 '17 at 23:01