18

I have been reading/researching the reason why HashMapis faster than HashSet.

I am not quite understanding the following statements:

  1. HashMap is faster than HashSet because the values are associated to a unique key.

  2. In HashSet, member object is used for calculating hashcode value which can be same for two objects so equals() method is used to check for equality. If it returns false, that means the two objects are different. In HashMap, the hashcode value is calculated using the key object.

  3. The HashMap hashcode value is calculated using the key object. Here, the member object is used to calculate the hashcode, which can be the same for two objects, so equals() method is used to check for equality. If it returns false, that means the two objects are different.

To conclude my question:

  1. I thought HashMap and HashSet calculate the hashcode in the same way. Why are they different?

  2. Can you provide a concrete example how HashSet and HashMap calculating the hashcode differently?

  3. I know what a "key object" is, but what does it mean by "member object"?

  4. HashMap can do the same things as HashSet, and faster. Why do we need HashSet? Example:

    HashMap <Object1, Boolean>= new HashMap<Object1, boolean>();
    map.put("obj1",true);  => exist
    map.get("obj1");  =>if null = not exist, else exist
    
4

2 回答 2

24

表现:

如果您查看 HashSet 的源代码(至少 JDK 6、7 和 8),它在内部使用 HashMap,因此它基本上与您使用示例代码所做的完全一样。

所以,如果你需要一个 Set 实现,你使用 HashSet,如果你需要一个 Map - HashMap。使用 HashMap 而不是 HashSet 的代码将具有与直接使用 HashSet 完全相同的性能。

选择正确的收藏

Map - 将键映射到值(关联数组) - http://en.wikipedia.org/wiki/Associative_array

Set - 一个不包含重复元素的集合 - http://en.wikipedia.org/wiki/Set_(computer_science)

如果您唯一需要收集的内容是检查其中是否存在元素 - 使用 Set。您的代码将更清晰,对其他人来说更容易理解。

如果您需要为元素存储一些数据 - 使用 Map.

于 2013-04-29T12:54:10.670 回答
12

这些答案都没有真正解释为什么HashMap 比 HashSet 快。他们都必须计算哈希码,但要考虑 HashMap 的键的性质——它通常是一个简单的字符串,甚至是一个数字。计算它的哈希码比计算整个对象的默认哈希码要快得多。如果 HashMap 的键与存储在 HashSet 中的对象相同,则性能上不会有真正的差异。不同之处在于 HashMap 的键是什么类型的对象。

于 2017-08-25T14:03:44.783 回答