java - How to convert from an immutable set to a hashset? -


i writing algorithm set undirected graph of objects. after adding , removing edges correctly specific elements in graph, reach point error.

exception in thread "main" java.lang.unsupportedoperationexception     @ java.util.collections$unmodifiablecollection.add(unknown source)     @ undirectedgraph.addedge(undirectedgraph.java:81) 

note after program had allowed me add edges graph , nothing has changed in way input objects addedge method. code 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 in graph.");      /* add edge in both directions. */     mgraph.get(one).add(two);     mgraph.get(two).add(one); } 

while running debugger, found @ beginning of code when mgraph.get(one) called returns hashset, when error occurs returns collections$unmodifiableset. why happening?

you don't here how mgraph populated. if of entries unmodifiable sets--especially if views of other data structures--then cause error message. chagrin of lot of developers, many operations on java collections classes optional, , may not supported implementors. collections.unmodifiablecollection returns read-only views, , method used views of other collections (such map.keyset).

to ensure hashset instances put mgraph, explicitly create new hashset<object> , addall source set, or use new hashset<object>(existingset) constructor.


Comments

Popular posts from this blog

toolbar - How to add link to user registration inside toobar in admin joomla 3 custom component -

linux - disk space limitation when creating war file -

How to provide Authorization & Authentication using Asp.net, C#? -