Java – use x = = y or (X-Y) = = 0 to control the problem of if conditions
My program includes the following code snippet, which is based on two variables temp Get (J1) and temp (J2) are executed according to whether they are equal
for (int j1 =0; j1<2;j1++) { for (int j2 =0; j2<2;j2++) { System.out.println("j1="+j1+"j2="+j2+" "+temp1.get(j1)+"----"+temp2.get(j2)); int xyz = temp1.get(j1)-temp2.get(j2); System.out.println("the difference is "+ xyz); if (temp1.get(j1)==temp2.get(j2)) { System.out.println("find match"); } } }
The program prints out like
j1 = 0j2 = 0 7698380 —- 7698380
The difference is 0
Even if the two values are temp1 Get (J1) and temp2 Get (J2) overlaps, and the "if" part is not passed If I put if (temp1. Get (J1) = = temp2 Get (J2)) to if (XYZ = = 0)
Then the result looks like
j1 = 0j2 = 0 7698380 —- 7698380
The difference is 0
Match found`
I think the two conditions controlling the if loop should be the same. Why are the results so different? Thank you very much for your answer
Solution
Well, temp1 Does get (J1) return an integer instead of an int? If so, the integers in question are different (i.e. not = =) Although they are the same from the perspective of equals()
Edit:
One way to solve this problem is to make temp1 and temp2 return int instead of integer You can use simple auto boxing here (or in this case auto boxing)
For example, your class is sithlord and your integer attribute is jedikills At present, your class looks like this:
public class SithLord { private Integer jediKills; public Integer getJediKills() { return jediKills; } }
All you have to do is change it to:
public class SithLord { private Integer jediKills; public int getJediKills() { return (jediKills == null ? 0 : jediKills); } }
Java will automatically convert the variable to int. (please note that I assume that a zero integer is zero here. This assumption may or may not apply to your class. But for the above class, because the Sith Lord will certainly publicize his killing.)
Or you can do this:
public class SithLord { private int jediKills; public int getJediKills() { return jediKills; } }
Either way, if you want to use the = = operator here, the class needs to return an int
As for why this might be useful to you, I can only speculate, because I don't see the code But to be sure, if the references on both sides of = = are the same, then = = will be true This happens if you have this control over the object But if you use auto@R_978_2419 @Original type, then you will give it up, because every time you auto boxing, Java will create a new wrapper for the original type for you And because they are new, they will not be the same reference
I hope it will help