My program includes the following code segment, which do sth based on whether two variables, temp.get(j1) and temp(j2) are equivalent or not.
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 sth like
j1=0j2=0 7698380—-7698380
the difference is 0
Even the two values, temp1.get(j1) and temp2.get(j2) do overlap, the “if” part just did not go through. If I change the if (temp1.get(j1)==temp2.get(j2)) to
if (xyz == 0)
Then the result will look like
j1=0j2=0 7698380—-7698380
the difference is 0
find match
`
I think the two conditions for controlling the if loop should be the same, why the result if so different? Thanks a lot for the answer.
Hm, does
temp1.get(j1)return anIntegerinstead of anint? If so, then theIntegers in question are not identical (i.e. not ==). Even though they are equal from the point of view ofequals().EDIT:
One way to solve this issue is to make temp1 and temp2 return an
intinstead of anInteger. You can use simple autoboxing (or, autounboxing in this case) here.Say for example that your class is
SithLordand your integer property isjediKills. Currently your class looks like this:All you have to do is change it to this:
And Java will automatically cast the variable to an
intfor you. (Note that I’m assuming here that a null Integer is a zero. That assumption may or may not work for your class. But for the class above it does, as a Sith lord would certainly advertise his kills.)Alternatively you can do this:
Either way the point is that the class needs to return an
intif you want to use the == operator here.As to why this may have worked in the past for you, I can only speculate since I haven’t seen the code. But it’s safe to say that == would be true iff the references on either side of the == are one and the same. That can happen if you’re exercising that sort of control over the objects. But if you autobox primitive types you give that up, because Java will create new wrappers around the primitive types for you each time you autobox. And because they’re new, they won’t be the same reference.
Hope that helps.