I am trying to determine whether the current object within a foreach loop nested inside of another foreach loop, which are both iterating over the same ArrayList, are currently both iterating over the same object. Due to the conventions of the foreach loop, there doesn’t appear to be a simple way to get the current index of the objects in the ArrayList to be able to compare the current objects for equality. Essentially, I would like to continue over the current object within the inner foreach loop if both of the foreach loops are currently iterating over the same object.
For example, given an ArrayList<Object> named objects:
for (Object a : objects) {
for (Object b : objects) {
//If both loops are currently iterating over the same object
//from the ArrayList objects, skip to the next iteration of the inner
//foreach loop
if (a == b) {
continue;
}
//If both foreach loops are not iterating over the same object
//execute some operation
}
}
Is using the == operator to test whether both objects that are currently being iterated over are the same object reliable, or is it better to simply use regular for loops instead and compare the objects based on their index?
It is OK to compare objects with
==in this case, but only if you didn’t put the same object in list multiple times. If you have same object in list on multiple places than this is not OK, and you should use standard for loop.