下面是我的代码。我成功地在 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>();
其余的将毫无问题地编译。
如果您不熟悉泛型,请参阅 tutorial和 comprehensive FAQ .您应该非常、非常很少使用原始类型(几乎从不)。如果你这样做,你应该能够配置你的 IDE 或编译器给你一个警告(例如,使用 -Xlint
for javac
)。
关于Java : Map showing error : bad operand type for binary operator "+",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23384651/