繁体   English   中英

将Double转换为Integer

[英]Casting Double to Integer

我遇到了强制性问题。 我似乎无法解决问题,因为一切似乎都井然有序。 我知道可以将Double包装器类显式转换为Integer包装器类,但是我的编译器无法识别。 我是否缺少明显的东西?

我得到的确切错误是:“不可转换类型;无法将'double'转换为'java.lang.Integer'。

谢谢你的帮助!

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

您不能直接从Double转换为Integer。 您需要执行以下操作:

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

如何将Double直接转换为int中所建议

尝试这个

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

希望它能解决您的问题

这似乎是最简单的:

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

首先,显式转换为int ,然后让编译器将int值自动装箱为Integer

请注意,这也消除了创建其他答案建议的各种辅助对象(额外的Double甚至是String )的需要。 这是我现在可以想到的最有效的方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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