Replacing a HashSet Java member

前端 未结 5 1451
我在风中等你
我在风中等你 2021-01-07 16:47

I have Set of that structure. I do not have duplicates but when I call: set.add(element) -> and there is already exact element I would like the old to be replac

5条回答
  •  心在旅途
    2021-01-07 17:13

    Try something as follows (this will only make sense if the equals and hashCode depends on one field, but the other fields could have different values):

    if(!set.add(obj)) {
        //set already contains the element (not the same object though) 
        set.remove(obj); //remove the one in  the set
        set.add(obj); //add the new one
    }
    

    Check out the documentation for the Set.add method

    If this set already contains the element, the call leaves the set unchanged and returns false.

提交回复
热议问题