Java:压缩 HashMap(类似于 ArrayList#trimToSize)
有没有一种方法可以像通过 ArrayList 的 trimToSize() 方法来压缩 HashMap 一样?
我能想到的一种方法是迭代当前映射中的所有条目并填充一个新条目,然后用新条目替换原始条目。
有更好的方法来实现这一点吗?
Is there a way to compact a HashMap in the sense that you can with an ArrayList through its trimToSize() method?
One way I can think of is to iterate through all of the entries in the present map and populate a new one, then replace the original with the new one.
Is there a better way to accomplish this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
好吧,您不需要手动进行迭代 - 您只需使用:
我相信这将为您完成所有迭代。 可能
clone()
会做同样的事情,但我不确定。不管怎样,我不相信你错过了任何东西——我不认为在当前的 API 中有任何执行“修剪”操作的方法。与 ArrayList 不同,这样的操作无论如何都会相当复杂(就像扩展一样) - 它不仅仅是创建一个新数组并执行单个数组复制的情况。条目需要重新分发。让
HashMap
在内部自行执行此操作的好处可能只是哈希码不需要重新计算。Well you don't need to go through iterating manually - you can just use:
I believe that will do all the iteration for you. It's possible that
clone()
will do the same thing, but I don't know for sure.Either way, I don't believe you're missing anything - I don't think there's any way of performing a "trim" operation in the current API. Unlike
ArrayList
, such an operation would be reasonably complex anyway (as expansion is) - it's not just a case of creating a new array and performing a single array copy. The entries need to be redistributed. The benefit of gettingHashMap
to do this itself internally would probably just be that the hash codes wouldn't need recomputing.如果您使用 trove 库,那么它支持哈希映射和哈希集修剪(请参阅 THashMap 对象,紧凑方法),最重要的是,当地图变得太稀疏时,自动修剪对象的删除。这应该比使用标准 java HashMap 实现构建新映射更快,因为(大概)它不必根据对象的哈希码重新排序对象,而只需使用它已经知道的顺序。
If you use the trove library instead this has support for hash map and hash set trimming (see THashMap object, compact method) and best of all, automatically trims on removal of objects when the map becomes too sparse. This should be quicker than building a new map using the standard java HashMap implementation as (presumably) it doesn't have to reorder the objects according to their hashcode, but can just use the order it already knows.