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; 
    }
ButtahNBred
  • 432
  • 1
  • 8
  • 24

3 Answers3

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?

Community
  • 1
  • 1
David Brossard
  • 13,584
  • 6
  • 55
  • 88
0

Try this

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

Hope it will resolve your issue

prashant thakre
  • 5,061
  • 3
  • 26
  • 39
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).

david a.
  • 5,283
  • 22
  • 24