简体   繁体   中英

Casting Double to Integer

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; 
    }

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?

Try this

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

Hope it will resolve your issue

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

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