-2
      HashMap<Integer, Integer> hmap = new HashMap<>();
      hmap.put(1,(int)128);
      hmap.put(2,(int)128);
      if((hmap.getOrDefault(2, -1)!=hmap.getOrDefault(1, -1)) {
          System.out.println("wrong");
          
      }
      System.out.println(hmap.get(2)+" "+hmap.get(1));
      if(hmap.get(2)==hmap.get(1)) 
      {
          System.out.println("wrong2");
      }

The above code output on console is wrong In the above case, the output should be wrong2

If I typecast value to int then it shows the output as wrong2

      HashMap<Integer, Integer> hmap = new HashMap<>();
      hmap.put(1,(int)128);
      hmap.put(2,(int)128);
      if((int)hmap.getOrDefault(2, -1)!=(int)hmap.getOrDefault(1, -1)) {
          System.out.println("wrong");
          
      }
      System.out.println(hmap.get(2)+" "+hmap.get(1));
      if((int)hmap.get(2)==(int)hmap.get(1)) 
      {
          System.out.println("wrong2");
      }
  • Does this answer your question? [How to properly compare two Integers in Java?](https://stackoverflow.com/questions/1514910/how-to-properly-compare-two-integers-in-java) – akuzminykh Jul 07 '20 at 17:09
  • 1
    Your code doesn't compile. Always include the actual code. – jarmod Jul 07 '20 at 17:10
  • auto boxing and unboxing can be tricky if you don't understand exactly what is going on. – Henry Jul 07 '20 at 17:13
  • @Manav Dawar, Yeah, you have to either downcast it to int or use the intValue() and compare the results. `(int)hmap.get(1)` or `hmap.get(1).intValue()` – Govind Jul 07 '20 at 17:16

1 Answers1

0

If you have an object, in your case Integer, you shouldn't use != or == in this case, you should use the method .equals(), as explained here https://www.geeksforgeeks.org/difference-equals-method-java/