简体   繁体   中英

Java retrieve value from TreeMap<String, TreeMap<String, Integer>>

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?

.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");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM