英文:
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 <E> Set<E> newSetFromMap(Map<E,Boolean> 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<E, Boolean>
在类型安全性方面是必需的。
这种限制性的类型也有助于鼓励正确的使用,如文档所述:
> 在调用此方法时,指定的map必须为空,
> 并且在此方法返回后不应直接访问它。如果map是空的,则可以确保满足这些条件,
> 直接将map传递给此方法,并且不保留对map的任何引用,如以下代码片段所示:
>
> Set<Object> weakHashSet = Collections.newSetFromMap(
> new WeakHashMap<Object, Boolean>());
如果该方法接受了Map<E, Object>
,就像在理论上可能的情况下,很容易传入已经包含非布尔值的现有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<E, Boolean>
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<E, Object>
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论