java如何更新映射中的值?
我正在使用TreeMap<Integer,Object>()
来存储值
现在我的Object
有一个组件Object.value()
,它根据从文件读取的值不断递增
因此,我评估密钥是否存在,是否需要更新值
我不明白如何在Java中更新Map
中的值
我不能仅仅替换整个记录,因为需要将新值添加到现有记录值中
有没有比使用地图更好的方法?我用了一张地图,因为我会一直找钥匙
有什么建议吗
你可以在下面搜索框中键入要查询的问题!
我正在使用TreeMap<Integer,Object>()
来存储值
现在我的Object
有一个组件Object.value()
,它根据从文件读取的值不断递增
因此,我评估密钥是否存在,是否需要更新值
我不明白如何在Java中更新Map
中的值
我不能仅仅替换整个记录,因为需要将新值添加到现有记录值中
有没有比使用地图更好的方法?我用了一张地图,因为我会一直找钥匙
有什么建议吗
# 1 楼答案
如果您希望能够快速访问键值对,那么使用映射是正确的。如果您的值只是
MyObjects
和.value()
,您不能获取对象并重置该值吗我在这里使用MyObject,因为海报使用
Object
表示示例类型# 2 楼答案
我不知道你想做什么,但是如果你只想用键存储对象,你应该使用哈希表。它允许将关键点映射到对象
希望这有帮助
# 3 楼答案
您的“对象”需要有一个更新值的setter。因此,您只需从映射中检索有问题的对象,调用该对象上的setter,et voila。您必须注意的唯一障碍是,无论您在
setXXX
方法中做什么,都不会改变equals
和hashCode
方法的结果,因为这违反了TreeMap
所隐含的不变量,并将导致不可预测的行为。您的对象可能如下所示:您可以将它从
TreeMap
中拉出,调用increment()
,而不必更改TreeMap
本身的内容