如何有效地比较集合? [英] How to efficiently compare Sets?

查看:137
本文介绍了如何有效地比较集合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出两个集合:如何在Java中有效地比较它们?

Given two Sets: how to compare them efficiently in Java?


  • (a)将它们保持为列表 s,对它们进行排序并进行比较。 (可比较

  • (b)将它们保留为设置并进行比较集合的 hashCode

  • (a) keep them as Lists, sort them and compare them. (Comparable)
  • (b) keep them as Sets and compare the hashCode of the Sets?

背景:

需要进行许多比较
设置很小(通常每组<5个元素)。

many comparisons need to be done Sets are small (usually < 5 elements per set).

推荐答案

比较两组的正确方法是使用 等于方法。我不担心性能,除非您已经证明这是导致性能问题的代码的一部分(我怀疑)。考虑到你的集合的大小(5个元素),这将非常快(可能是亚毫秒)。

The proper way to compare two sets is to use the equals method. I would not worry about performance unless you have proven that this is a part of your code that is causing performance issue (which I doubt). And considering the size of your sets (5 elements) this will be very fast (probably sub millisecond).


将它们保存为列表,排序他们并比较他们。 (可比)

keep them as lists, sort them and compare them. (comparable)

肯定会变慢,因为你需要复制元素,对它们进行排序并进行比较。

will certainly be slower as you will need to copy the elements, sort them and compare.


将它们保存为集合并比较集合的哈希码?

keep them as sets and compare the hashcode of the sets?

如果2个集合相等(具有相同的内容),则它们将具有相同的哈希码。倒数不是真的:具有不同内容的2个集合可以具有相同的散列码。另请注意,对于 HashSet ,例如,通过迭代所有元素来计算哈希码,使其不是自由操作。

if 2 sets are equal (have the same content) they will have the same hashcode. The reciprocal is not true: 2 sets with different content may have the same hashcode. Also note that for a HashSet for example, the hashcode is calculated by iterating over all the elements so it is not a free operation.

这篇关于如何有效地比较集合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆