`newSetFromMap` 使用布尔值

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

newSetFromMap use of Boolean

问题

Collections.newSetFromMap方法具有以下签名:

public static <E> Set<E> newSetFromMap(Map<E, Boolean> map)

对于地图的布尔参数的重要性是什么?如果我只对E参数类型感兴趣,那么我需要关注它吗?

英文:

The Collections.newSetFromMap method has the following signature:

public static &lt;E&gt; Set&lt;E&gt; newSetFromMap​(Map&lt;E,​Boolean&gt; map)

What is the significance of the Boolean parameter for the map? Is it something that I need to be concerned with if I am only interested in the E parameter type?

答案1

得分: 1

newSetFromMap的工作方式是使用提供的Map,在add操作时向其中放入一个虚拟值。所有其他操作只是在map的keySet上执行。它恰好使用Boolean.TRUE作为虚拟值(参见源代码),因此输入类型Map&lt;E, Boolean&gt;在类型安全性方面是必需的。

这种限制性的类型也有助于鼓励正确的使用,如文档所述:

> 在调用此方法时,指定的map必须为空,
> 并且在此方法返回后不应直接访问它。如果map是空的,则可以确保满足这些条件,
> 直接将map传递给此方法,并且不保留对map的任何引用,如以下代码片段所示:
>
> Set<Object> weakHashSet = Collections.newSetFromMap(
> new WeakHashMap<Object, Boolean>());

如果该方法接受了Map&lt;E, Object&gt;,就像在理论上可能的情况下,很容易传入已经包含非布尔值的现有map,这是不鼓励的,可能会导致意外行为。

所以,只要根据文档中的规定正确使用该方法,就没有什么可担心的。

英文:

The way newSetFromMap works is it uses the provided Map, and puts a dummy value in it on add. All other operations simply operate on the keySet of the map. It happens to use Boolean.TRUE as the dummy value (see the source), so the input type Map&lt;E, Boolean&gt; is required for this to be type-safe.

The restrictive type also helps encourage proper usage, per the docs:

> The specified map must be empty at the time this method is invoked,
> and should not be accessed directly after this method returns. These
> conditions are ensured if the map is created empty, passed directly to
> this method, and no reference to the map is retained, as illustrated
> in the following code fragment:
>
> Set<Object> weakHashSet = Collections.newSetFromMap(
> new WeakHashMap<Object, Boolean>());

If the method accepted a Map&lt;E, Object&gt; as it theoretically could, it would be easy to pass in an existing map that already contains non-boolean values, which is discouraged and could result in surprising behaviour.

So no, it's nothing to be concerned about so long as you are using the method correctly as specified in the docs.

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

发表评论

匿名网友

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

确定