如何从不可变集转换为哈希集?

How to convert from an immutable set to a hashset?

我正在编写一个算法来建立 objects 的无向图。在正确添加和删除图表中特定元素的边后,我到达了一个特定点,并出现此错误。

Exception in thread "main" java.lang.UnsupportedOperationException
    at java.util.Collections$UnmodifiableCollection.add(Unknown Source)
    at UndirectedGraph.addEdge(UndirectedGraph.java:81)

请注意,这是在程序允许我向图形添加边之后,并且我在 addEdge 方法中输入 objects 的方式没有任何变化。 addEdge 的代码是:

private final Map<Object, Set<Object>> mGraph = new HashMap<Object, Set<Object>>();

public void addEdge(Object one, Object two) {
    /* Confirm both endpoints exist. */
    if (!mGraph.containsKey(one) || !mGraph.containsKey(two))
        throw new NoSuchElementException("Both nodes must be in the graph.");

    /* Add the edge in both directions. */
    mGraph.get(one).add(two);
    mGraph.get(two).add(one);
}

而运行调试器,我发现在代码的开头当mGraph.get(one)被称为returns一个HashSet,但是当错误发生时它returns Collections$UnmodifiableSet.为什么会这样?

你不在这里说 mGraph 是如何填充的。如果任何条目是不可修改的集合——特别是如果那些是某些其他数据结构的视图——那么它可能会导致该错误消息。令许多开发人员懊恼的是,Java 集合 类 上的许多操作都是可选的,甚至可能不支持实现者。 Collections.unmodifiableCollection returns只读视图,该方法常用于其他集合的视图(如Map.keySet)。

为了确保只有 HashSet 实例被放入 mGraph,显式地从源集中创建一个 new HashSet<Object>addAll,或者使用 new HashSet<Object>(existingSet) 构造函数。