0

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?

1
  • I find this strange. Normally .get would return null if the key didn't exist (or happened to map to null), and you'd get a NullPointerException instead. Commented May 16, 2015 at 15:48

1 Answer 1

2

.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");
Sign up to request clarification or add additional context in comments.

6 Comments

I'm using it in a loop so I can make an adjacency matrix based on those values. So I cannot use "A" or "B" but have to use i or j which are integers(from my nested for loops)
I think your design's wrong, then. You're mapping String to String to int; you have no other way to get through the mapping with anything other than Strings.
What would be a better way to make it?
That's a broader question than what you've phrased here, I'm afraid. Although, if you're looking for hints on adjacency matrices, then you should search this site. There are a lot of approaches to it in Java.
I edited the question a bit, but thanks anyways. I'll look into it.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.