Java set add 放置自定义添加实现
我需要使用 Set
接口的实现来存储 MyObject
类型的对象。
MyObject
有两个字段:id
和 score
。为了使 MyObject
相等,仅使用 id
。我需要使用的功能之一是能够支持当两个 MyObject
(具有相同的 id
)时能够添加 score
s) 被插入到该集合中。
目前,我正在使用 TreeSet
并且它没有按照我希望的方式工作。
Set<MyObject> container = new TreeSet<MyObject>();
MyObject obj1 = new MyObject(12, 0.345);
container.add(obj1);
MyObject obj2 = new MyObject(12, 0.1);
container.add(obj2);
我希望容器具有 Myobject(12,0.445)
但它是一个集合,容器具有 MyObject(12, 0.1)
。
有什么我可以使用的东西可以给我我想要的东西吗?
I need to be using an implementation of Set
interface for storing objects of type MyObject
.
MyObject
has two fields: id
and score
. For equality on MyObject
, only id
is used. One of the functionality I need to use is to be able to support to be able to add score
s when two MyObject
s (with same id
s) are inserted into this set.
Currently, I am using TreeSet
and its isn't working the way I want it to work.
Set<MyObject> container = new TreeSet<MyObject>();
MyObject obj1 = new MyObject(12, 0.345);
container.add(obj1);
MyObject obj2 = new MyObject(12, 0.1);
container.add(obj2);
I want container to have Myobject(12,0.445)
but it being a set, the container has MyObject(12, 0.1)
.
Is there something I can use which will give me what I am looking for?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
为此,您应该使用
Map
:或者
然后您可以在容器上调用
get
来查看该对象是否已经存在,并增加其分数。Set
对您不起作用,因为没有有效的方法从 Set 中获取obj1
。You should use a
Map
for this:or
Then you can call
get
on the container to see if the object is already there, and increment its score.A
Set
will not work for you because there is no efficient way of getting theobj1
from the Set.更改代码/类以遵循以下语义
还有其他方法可以执行此操作,例如扩展 TreeSet 并覆盖 add() 方法或通过委托(建议使用 Guava 的转发集合),但我提供的解决方案简单而明确。
更正:按照 Thomas 的建议,使用 TreeMap 而不是 TreeSet
Change the code/classes to follow the below semantics
There are other ways of doing this like extending the TreeSet and overriding the add() method or by delegation (suggest using Guava's forwarding collection) but the solution I provided is simple and explicit.
Correction: Use TreeMap instead of TreeSet as suggested by Thomas
TreeSet 实现的 add 方法如下所示
,其中 PRESENT 是一个虚拟对象,用于指示添加的对象已存在。
您可以对 TreeSet 进行子类化以使用分数总和而不是虚拟对象
,或者如果可能的话,完全摆脱 Set 并直接使用 Map,如 @Thomas 所说
The add method for the TreeSet implementation looks like this
where PRESENT is a dummy object used to indicate the object added already exists.
you could subclass TreeSet to use the score sum instead of a dummy object
or, if possible, get rid of the Set altogether and instead use directly the Map as @Thomas says