I have a hashmap in the form of HashMap<Vertex, HashSet<Edge>>
and want to be able to return a set of keys from this.
public Set<Vertex> getVertices()
{
return edgeLists.keySet();
}
This is the method that i use to do that.
However when i run this method for example.
HashSet<Vertex> blah = (HashSet<Vertex>)graph.getVertices();
for (Vertex v : blah)
{
System.out.println(v);
}
i get the following error
java.lang.ClassCastException: java.util.HashMap$KeySet cannot be cast to java.util.HashSet
Any ideas on how to solve this issue.
Thanks in advance
The key to your quandary is in the cast exception…
java.lang.ClassCastException: java.util.HashMap$KeySet cannot be cast to java.util.HashSet
The Set “type” in the HashMap is of type KeySet. You’re trying to cast it to a HashSet which isn’t allowed. (HashSet extends AbstractSet and it is unclear what KeySet extends because I think it is an Inner Class of HashMap. However, they don’t seem to be in the same class hierarchy.)
Try casting to the generic Set interface instead.
Best of Luck.
Cheers for the advice.
Set<Vertex> ver = edgeLists.keySet();
HashSet<Vertex> output = new HashSet<Vertex>();
for (Vertex v : ver)
{
output.add(v);
}
return output;
The following code worked - although probably not the best it could be it suffices for my needs.
Do you have to use a HashSet? It is typically best to just use the interface Set. That way you really don’t care what the implementation of the Set is behind the scenes.
Best of Luck.
I dont have to use that, Sorry - i’m not that good at programming, only a first year computer science student. I see your logic there though and why i should change it to that.
Cheers for the advice!
You’re welcome. In my opinion it is almost always best to program to the interface instead of a specific data type if an interface exists.
BTW, no reason to apologize. We all started out at some point. 