This question already has an answer here:
这个问题在这里已有答案:
- Difference between HashSet and HashMap? 21 answers
HashSet和HashMap之间的区别? 21个答案
I have Question regarding the best practice of using a Collection
regarding the memory. I need to call a method which returns pairs of (Key,Value) frequently, so which way is the best, using HashMap
or creating an Object that contains Key and value and save this object in a HashSet
?
关于使用集合关于内存的最佳实践,我有疑问。我需要调用一个经常返回(Key,Value)对的方法,这样哪种方式最好,使用HashMap或创建一个包含Key和value的Object并将该对象保存在HashSet中?
Thanks & Regards.
感谢和问候。
1 个解决方案
#1
4
It depends on whether you need to search the data structure based on the key alone or both the key and the value.
这取决于您是否需要仅根据密钥或密钥和值来搜索数据结构。
-
If you search by the key alone (i.e.
map.containsKey(key)
), you should use aHashMap
.如果单独使用密钥进行搜索(即map.containsKey(key)),则应使用HashMap。
-
If you search for existence of a key-value pair (i.e.
set.contains(new Pair(key,value)
), you should use aHashSet
that contains those pairs.如果搜索键值对的存在(即set.contains(new Pair(key,value)),则应使用包含这些对的HashSet。
Another thing to consider is how you determine the uniqueness of the elements. If it is determined by the key alone, you should use a HashMap
. If it is determined by both key and value (i.e. you can have the same key appear twice with different values), you must use HashSet
, since HashhMap
doesn't allow the same key to appear more than once.
另一件需要考虑的事情是如何确定元素的唯一性。如果仅由密钥确定,则应使用HashMap。如果它由键和值确定(即,您可以使用不同的值出现两次相同的键),则必须使用HashSet,因为HashhMap不允许同一个键出现多次。
#1
4
It depends on whether you need to search the data structure based on the key alone or both the key and the value.
这取决于您是否需要仅根据密钥或密钥和值来搜索数据结构。
-
If you search by the key alone (i.e.
map.containsKey(key)
), you should use aHashMap
.如果单独使用密钥进行搜索(即map.containsKey(key)),则应使用HashMap。
-
If you search for existence of a key-value pair (i.e.
set.contains(new Pair(key,value)
), you should use aHashSet
that contains those pairs.如果搜索键值对的存在(即set.contains(new Pair(key,value)),则应使用包含这些对的HashSet。
Another thing to consider is how you determine the uniqueness of the elements. If it is determined by the key alone, you should use a HashMap
. If it is determined by both key and value (i.e. you can have the same key appear twice with different values), you must use HashSet
, since HashhMap
doesn't allow the same key to appear more than once.
另一件需要考虑的事情是如何确定元素的唯一性。如果仅由密钥确定,则应使用HashMap。如果它由键和值确定(即,您可以使用不同的值出现两次相同的键),则必须使用HashSet,因为HashhMap不允许同一个键出现多次。