java - 为什么需要从 Integer 转换为 int

标签 java

我在使用 TreeMap 时遇到了问题。

    Map<Integer, Integer> a = new TreeMap<Integer, Integer>();
    a.put(5,1);
    a.put(3,2);
    a.put(4,3);
    int target = 7;
    System.out.println(target - a.get(5)); //line 6
    for(Map.Entry b : a.entrySet()){
        System.out.println(target - b.getValue()); //line 8
    }

上面的代码给了我一个编译错误。但是,当我将第 8 行更改为:

    Map<Integer, Integer> a = new TreeMap<Integer, Integer>();
    a.put(5,1);
    a.put(3,2);
    a.put(4,3);
    int target = 7;
    System.out.println(target - a.get(5)); //line 6
    for(Map.Entry b : a.entrySet()){
        System.out.println(target - (int) b.getValue()); //line 8
    }

然后就可以了。谁能给我一些想法,为什么我不需要在第 6 行进行任何更改但需要在第 8 行将 Integer 转换为 int?

最佳答案

您忽略了 for 语句中的“原始类型”警告。应该是:

    for(Map.Entry<Integer,Integer> b : a.entrySet()) {
        ...

原始类型会导致 getValue() 返回 Object。如果你提供了类型参数,那么编译器就知道它会返回 Integer,这会被自动拆箱。

关于java - 为什么需要从 Integer 转换为 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35595997/

相关文章:

java md5 散列显示垃圾

java - 读取文件页眉和页脚的程序

java - 模拟注入(inject)的 SessionContext

java - 尽管变量与其他有效的变量相同,但它并未初始化

java - jar 上的 Maven 项目许可证报告

java - 在android中使用volley发送json数组将mysql中的多条记录添加到php脚本

java - 用 java 以纯文本形式编写耸肩 ASCII 表情符号¯\_(ツ)_/¯

java - 如何在 neo4j 中使用条件匹配

java - 为什么invokeLater在主线程中执行?

java - 在 Java 中为多种对象类型创建方法