Java : Map showing error : bad operand type for binary operator "+"

标签 java map

下面是我的代码。我成功地在 Map 中添加了值 但是当尝试获取特定键的值并更新它时,则没有任何值获取

出现错误:二元运算符“+”的错误操作数类型

    Map map = new HashMap();

    System.out.println("Enter the number :");
    int k=sc.nextInt();    
    System.out.println(map.get(k));     

    System.out.println("Enter the value:");
    int v=sc.nextInt(); 

    map.put(k, map.get(k)+v);   //getting error here: bad operand type for binary operator "+"

最佳答案

您没有使用泛型(您使用的是 raw type),因此编译器不知道映射中值的类型 - map.get(k) 返回Object 就编译器而言,没有 +(Object, int) 运算符。

只需在您的 map 声明和初始化中使用泛型:

// Java 7 and later, using the "diamond operator"
Map<Integer, Integer> map = new HashMap<>();

或者:

// Java 5 and 6 (will work with 7 and later too, but is longer)
Map<Integer, Integer> map = new HashMap<Integer, Integer>();

其余的将毫无问题地编译。

如果您不熟悉泛型,请参阅 tutorialcomprehensive FAQ .您应该非常、非常很少使用原始类型(几乎从不)。如果你这样做,你应该能够配置你的 IDE 或编译器给你一个警告(例如,使用 -Xlint for javac)。

关于Java : Map showing error : bad operand type for binary operator "+",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23384651/

相关文章:

java - JScrollPane 不添加组件

java - 使用泛型可以解决我的问题吗?

c++ - 双映射结构实现?

java - 读取文本字段数组

java - 线程池性能

java - 泛型 0 无法转换为 java.lang.Short

iphone 默认 map 应用程序以不同语言打开

ios - 如何使 MKMapView 上注释的 Popover 像 Apple 一样随 map 滚动?

java - JPA实体映射到特定表

java - Eclipse 在启动屏幕后崩溃