比较作为映射键和值的集合的大小

huangapple go评论75阅读模式
英文:

Comparing sizes of sets that are keys and values of a map

问题

考虑一个映射  m,其中 m 的类型为  HashMap 或者  TreeMap。假设 s1 和 s2 都是集合,类型为  HashSet 或者  TreeSet,其中 s1 是 m 中键的集合, s2 是 m 中相应值的集合。哪个命题必定成立?

a. s1.size() > s2.size()

b. s1.size() <= s2.size()

c. s1.size() >= s2.size()这是正确答案。

d. s1.size() == s2.size()

e. s1.size() < s2.size()

我之前以为是选项 "b",因为一个键可以有多个值,但事实证明答案是 "c",这里可能有比值更多的键。然而,我在理解为什么 "b" 错误而 "c" 正确方面遇到了问题。有人可以帮我理解为什么 "b" 是错误的,而 "c" 是正确的吗?

英文:

>Consider a map  m, where  m  is of type  HashMap  or  TreeMap.  Suppose  s1  and  s2  are both sets, of type  HashSet  or  TreeSet, where  s1  is the set of keys in  m, and  s2 is the set of corresponding values in  m.  Which  must  be true?

a. s1.size() > s2.size()

b. s1.size() <= s2.size()

c. s1.size() >= s2.size()This is the correct answer.

d. s1.size() == s2.size()

e. s1.size() < s2.size()

I had thought it would be "b" since a key can have many values, but it turns out the answer is c, where there may be more keys than values. However, I'm having problems understanding the answer provided (c)—could anyone help me understand why b is wrong and c is right?

答案1

得分: 1

你的理解是错误的:一个键最多只有一个类型为V的值。(这个V可以是像集合或列表这样的容器,但在映射中它是单个值。)多个键可以有相同的值(事实上,这就是HashSet本身的实现方式,建立在HashMap之上)。

英文:

You have it backwards: A key has at most one value of type V. (That V could be a container like a set or list, but it is a single value in the map.) Multiple keys could have the same value (this is in fact how HashSet itself is implemented, on top of a HashMap).

答案2

得分: 1

一个键只能有一个值。该值可以是一个包含多个元素的对象。但每个键只有一个值。

在映射中,键是唯一的,但值不必是唯一的。在下面的示例中,有 3 个唯一的键,但只有 1 个唯一的值:

Map<String, String> map = new HashMap<>();
map.put("key1", "elephant");
map.put("key2", "elephant");
map.put("key3", "elephant");

因此,如果你从值的列表中创建一个集合(Set),集合中唯一的对象将是 "elephant"。但如果你从键创建一个集合(Set),你会得到 3 个对象 "key1"、"key2" 和 "key3"。所以键的数量大于值的数量。

英文:

A key can only have 1 value. The value could be an object, that could contain multiple things. But you only have 1 value per key.

In a Map your keys are guaranteed to be unique, but the values do not have to be unique. In the following example there are 3 unique keys, but only 1 unique value:

Map&lt;String, String&gt; map = new HashMap&lt;&gt;();
map.put(&quot;key1&quot;, &quot;elephant&quot;);
map.put(&quot;key2&quot;, &quot;elephant&quot;);
map.put(&quot;key3&quot;, &quot;elephant&quot;);

So if you create a Set from the list of values, the only object in the Set will be "elephant". But if you create a Set from the keys then you get 3 objects "key1", "key2", and "key3". So the count of keys is greater than the count of values.

huangapple
  • 本文由 发表于 2020年4月9日 10:46:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/61113157.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定