0

I am running into a casting issue. I cannot seem to figure out the problem since everything appears to be in order. I understand that to explicitly cast from the Double wrapper class to the Integer wrapper class it can be done however, my compiler does not recognize it. Am I missing something obvious?

The exact error I'm getting is : "Inconvertible types; cannot cast 'double' to 'java.lang.Integer'.

Thanks for your help!

private HashMap<String, Integer> shortestPath(String currentVertex, Set<String> visited) { double tempVal = Double.POSITIVE_INFINITY; String lowestVertex = ""; Map<String, Integer> adjacentVertex = this.getAdjacentVertices(currentVertex); HashMap<String, Integer> lowestCost = new HashMap<String, Integer>(); for(String adjacentNames : adjacentVertex.keySet()) { Integer vertexCost = adjacencyMap.get(currentVertex).get(adjacentNames); if(!visited.contains(adjacentNames) && (vertexCost < tempVal)) { lowestVertex = adjacentNames; tempVal = vertexCost; } } lowestCost.put(lowestVertex, (Integer)tempVal); return lowestCost; } 
4
  • 3
    possible duplicate of How to convert Double to int directly? Commented Aug 6, 2014 at 11:35
  • @DavidBrossard no it is not. OP wants to Casting double to Integer Commented Aug 6, 2014 at 11:36
  • Why have tempVal declared as a double when it appears that you always want an int? Commented Aug 6, 2014 at 11:40
  • tempVal had to be declared as a double rather than an int because of the Positive_Infinity value. All I had to do was change double tempVal to Double tempVal. Commented Aug 6, 2014 at 11:42

3 Answers 3

4

You cannot cast directly from Double to Integer. You need to do the following:

Double d = new Double(1.23); int i = d.intValue(); 

as suggested in How to convert Double to int directly?

Sign up to request clarification or add additional context in comments.

6 Comments

OP wants to Casting double to Integer
@RuchiraGayanRanaweera and what does the above code do?
OP want Integer not int
@RuchiraGayanRanaweera Integer and int autobox just fine, so where is the problem?
That segment of code is called by another function to find the shortest path for Dijkstras algorithm.
|
0

Try this

 lowestCost.put(lowestVertex, (Integer) new Double(tempVal).intValue()); 

Hope it will resolve your issue

Comments

0

This seems to be the easiest:

lowestCost.put(lowestVertex, (int) tempVal); 

First, explicitely cast to an int, then have the compiler to autobox the int value to an Integer.

Note that this also eliminates the need to create various helper throwaway objects that other answers suggest (an extra Double or even a String). It is the most efficient way I can think of (at this moment).

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.