Java:压缩 HashMap(类似于 ArrayList#trimToSize)

发布于 2024-12-09 20:25:47 字数 138 浏览 0 评论 0原文

有没有一种方法可以像通过 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

何必那么矫情 2024-12-16 20:25:47

好吧,您不需要手动进行迭代 - 您只需使用:

map = new HashMap<String, String>(map); // Adjust type arguments as necessary

我相信这将为您完成所有迭代。 可能 clone() 会做同样的事情,但我不确定。

不管怎样,我不相信你错过了任何东西——我不认为在当前的 API 中有任何执行“修剪”操作的方法。与 ArrayList 不同,这样的操作无论如何都会相当复杂(就像扩展一样) - 它不仅仅是创建一个新数组并执行单个数组复制的情况。条目需要重新分发。让 HashMap 在内部自行执行此操作的好处可能只是哈希码不需要重新计算。

Well you don't need to go through iterating manually - you can just use:

map = new HashMap<String, String>(map); // Adjust type arguments as necessary

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 getting HashMap to do this itself internally would probably just be that the hash codes wouldn't need recomputing.

墨小沫ゞ 2024-12-16 20:25:47

如果您使用 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文