Reputation: 1374
I'm pretty new to Maps and I'm quite stuck. I have the following TreeMap:
TreeMap<String, Map<String, Integer>> routes = new TreeMap<String, Map<String, Integer>>();
Let's say, for example, my TreeMap is filled as follows:
{A={B=10, C=15, D=20}, B={C=35, D=25}, D={C=30}}
Now I'm trying to print out the Integer value from my TreeMap and assign it to an int x = routes.get(0).get(0)
but I'm getting the following error:
Exception in thread "main" java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer
After a bit of reading, I understood that I'm trying to cast an String object into an Integer object which is not correct and that’s why Java throws the error meaning my x
is being assigned to B
and not 10
.
So my question is how do I assign x to the value of 10?
Upvotes: 0
Views: 121
Reputation: 106518
.get()
is attempting to use the key of the map that you've declared. Since you want to find the value within Map[A][B], then you should refer to it as such:
int x = routes.get("A").get("B");
Upvotes: 2