1

In my below code i check the two infocode if it exist show msg MSG_SAME_INFO_ALREADY_EXISTS but the issue is that when i compare two infocode the infocode value is same but it cannot enter the loop .

What i am wrong in below code ?

if (folderInfoData.getFolderInforecord().getInfoCode() == map.get("infoCode")) {
    showError(pageResourceBundle.getText("MSG_SAME_INFO_ALREADY_EXISTS"));
    return;
    }

Both Debug value given below :

the both folderInfoData.getFolderInforecord().getInfoCode() and map.get("infoCode") infocode return integer given below.

enter image description here enter image description here

Can anyone tell me how can resolve this issue ?

Thanks

Sitansu
  • 3,225
  • 8
  • 34
  • 61
  • possible duplicate of [Comparing Integer objects vs int](http://stackoverflow.com/questions/4036167/comparing-integer-objects-vs-int) – devnull Jan 13 '14 at 09:48

2 Answers2

5

You are comparing objects - Integers, the == operator might work only for numbers between [-128,127]. Look at the JLS:

If the value p being boxed is true, false, a byte, or a char in the range \u0000 to \u007f, or an int or short number between -128 and 127 (inclusive), then let r1 and r2 be the results of any two boxing conversions of p. It is always the case that r1 == r2.

Since that values you're comparing are not in the mentioned range, the result will be evaluated to false. You should use Integer#equals instead.

Maroun
  • 94,125
  • 30
  • 188
  • 241
  • 3
    It doesn't even work reliably in that area, if one of the `Integer` values is not produced by autoboxing: `Integer i1 = 100; Integer i2 = new Integer(100); System.out.println(i1 == i2);`. This will print `false`. You should **always** use `equals` to compare `Integer`, no matter which range they are in. – Joachim Sauer Jan 13 '14 at 09:49
  • @JoachimSauer That's how downvotes should be clarified :) Comments like that are extremely helpful for me and for OP. – Maroun Jan 13 '14 at 09:52
2

You are comparing Object with == that is the issue. use equals() instead of ==

Why should we use equals()?

Read this link for more info. and ᴍaroun ᴍaroun answer describe more.

Community
  • 1
  • 1
Ruchira Gayan Ranaweera
  • 34,993
  • 17
  • 75
  • 115