Replacing a HashSet Java member

前端 未结 5 1494
我在风中等你
我在风中等你 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:26

    Do a remove before each add:

     someSet.remove(myObject);
     someSet.add(myObject);
    

    The remove will remove any object that is equal to myObject. Alternatively, you can check the add result:

     if(!someSet.add(myObject)) {
         someSet.remove(myObject);
         someSet.add(myObject);
     }
    

    Which would be more efficient depends on how often you have collisions. If they are rare, the second form will usually do only one operation, but when there is a collision it does three. The first form always does two.

提交回复
热议问题