Below is my code. i am successfully adding values in Map but when try to get value of particular key and update it then no value getting
getting error : bad operand type for binary operator "+"
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 "+"
You're not using generics (you're using a raw type instead), so the compiler has no idea what type of value is in the map - map.get(k)
returns Object
as far as the compiler is concerned, and there's no +(Object, int)
operator.
Just use generics in your map
declaration and initialization:
// Java 7 and later, using the "diamond operator"
Map<Integer, Integer> map = new HashMap<>();
Or:
// Java 5 and 6 (will work with 7 and later too, but is longer)
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
The rest will compile with no problems.
If you're new to generics, see the tutorial and the comprehensive FAQ. You should very, very rarely use raw types (almost never). You should be able to configure your IDE or compiler to give you a warning if you do so (e.g. with -Xlint
for javac
).
See more on this question at Stackoverflow