Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 "+"
like image 698
Naresh Avatar asked Jun 28 '26 19:06

Naresh


2 Answers

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).

like image 160
Jon Skeet Avatar answered Jun 30 '26 08:06

Jon Skeet


Your map is a raw HashMap. So, the value can be any type. You can't use + operator with any type of object in java.

To overcome this, define a generic map like below

Map<Integer, Integer> map = new HashMap<>(); //Java 7 version

Map<Integer, Integer> map = new HashMap<Integer, Integer>(); //Java 5 and later versions

Here, both key and value are type of Integer, so you can use + operator with them

like image 37
Abimaran Kugathasan Avatar answered Jun 30 '26 08:06

Abimaran Kugathasan