Replacing a HashSet Java member(替换 HashSet Java 成员)
问题描述
我有那个结构的集合.我没有重复,但是当我打电话时:set.add(element)
-> 并且已经有确切的元素我想替换旧的.
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 replaced.
推荐答案
每次添加前做一个remove:
Do a remove before each add:
remove 将删除任何等于 myObject 的对象.或者,您可以检查添加结果:
The remove will remove any object that is equal to myObject. Alternatively, you can check the add result:
哪种方式更有效取决于您发生碰撞的频率.如果它们很少见,第二种形式通常只做一次操作,但当发生碰撞时,它会做三次.第一种形式总是做两个.
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.
这篇关于替换 HashSet Java 成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!