My program includes a code segment as following:

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));
       			
        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
j1=0j2=1 7698380----7726365
the difference is -27985
j1=1j2=0 7726365----7698380
the difference is 27985
j1=1j2=1 7726365----7726365
the difference is 0
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)

The result will look like
j1=0j2=0 7698380----7698380
the difference is 0
find match
j1=0j2=1 7698380----7726365
the difference is -27985
j1=1j2=0 7726365----7698380
the difference is 27985
j1=1j2=1 7726365----7726365
the difference is 0
find match
j1=0j2=0 7698380----7698380
the difference is 0
find match

The result is just what I expected. Can you let me know how does this happen? Thanks a lot.

What data type does the get() method return? What type is temp1?
The == operator is for comparing primitives.
For comparing the contents of objects use the .equals() method.

I defined and got temp1 this way:

ArrayList<ArrayList<Integer>> clusterApplyID1 = new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> temp1 = clusterApplyID1.get(i);

By the way, how to use .equals() method? Thanks.

What data type does the get() method return? What type is temp1?
The == operator is for comparing primitives.
For comparing the contents of objects use the .equals() method.

Since the arraylists contain Integers, there is the autoboxing and unboxing done by the compiler to screw things up. I don't know when and where that happens. It is often a surprise.

Can I assume that .equals() should be an robust approach to avoid these uncertainties? Thanks.

Since the arraylists contain Integers, there is the autoboxing and unboxing done by the compiler to screw things up. I don't know when and where that happens. It is often a surprise.

Did the use of equals() solve it for you?
Best only to use == with primitives or when you want to test if two object references (pointers) point to the same object.

Can I assume that .equals() should be an robust approach to avoid these uncertainties? Thanks.

Have a look at the documentation for Integer. It says

public boolean equals(Object obj)
Compares this object to the specified object. The result is true if and only if the argument is not null and is an Integer object that contains the same int value as this object.

... is that what you want to achieve (I think it probably is)?

This article has been dead for over six months. Start a new discussion instead.