I have an arrayList called A, say, which is non-empty.
I create another arrayList, B, and put in some elements of A.
for(someobject obj : A){
if(some_condition_is_met)
B.add(obj);
}
Then I do some stuff with B (never modifying, shuffling, or deleting objects from it. I pick an element of B, say B.get(i).
Now, I want to find B.get(i)'s position in A.
I tried
for(someobject obj : A){
if(obj.equals(B.get(i))
return A.lastIndexOf(obj);
}
return null;
But this kept returning null. That is, "equals" doesn't match the objects.
SO in my frustration I tried:
return A.get(A.lastIndexOf(B.get(i));
which caused an ArrayINdexOutOfBounds exception.
Any ideas what I should do? I've got a feeling I'm missing something obvious. One more point - this is an incredibly simplified explanation of what I'm doing. In the above example creating B might seem pointless, but it is necessary.
ANSWERS TO QUESTIONS:
1)The objects are custom objects. Ah,... I didn't override equals. That might be it.
2) I can be sure any object in B mst B in A because on creating B, first I remove all from it, just in case, then I add only object from A and I do not tamper with the objects once in B.
ArrayListcontain? If it's custom object, it might be because you didn't override theequals()method?Athat should matchB.get(i)?B; the default implementation ofequals()should therefore returntrueif the two references match.equals(). The OP is looking to compare two references to the same object, not two objects.