I am writing an algorithm to set up an undirected graph of objects. After adding and removing edges correctly to specific elements in the graph, I reach a certain point where I get this error.
Exception in thread "main" java.lang.UnsupportedOperationException
at java.util.Collections$UnmodifiableCollection.add(Unknown Source)
at UndirectedGraph.addEdge(UndirectedGraph.java:81)
Note that this is after the program had already allowed me to add edges to the graph and nothing has changed in the way I input objects into the addEdge method. The code for addEdge is:
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);
}
While running the debugger, I found that at the beginning of the code when mGraph.get(one) is called it returns a HashSet, but when the error occurs it returns Collections$UnmodifiableSet. Why is this happening?