IndexedContainer faulty?

I’ve got an indexed container and I need to go through all the items to change a property. I tried using a loop like this:

for(Object itemId : container.getItemIds()) {
            Item item = container.getItem(itemId);
            if (item != null) {
//use the item somehow
}}

Is my assumption wrong, that an item should actually never be null using this loop? The problem is, that it happens from time to time, that container.getItem(itemId) returns null, even though the itemId was fetched using the outher foreach loop.

Any ideas what might cause this issue, or a secure way to iterate over all items inside a container?

Thanks in advance!!

Yes, item should never be null in your case. Could it be some kind of a concurrency issue? Are you modifying the container at the same time as you loop through it (although, in that case you should get a ConcurrencyException, with the code provided).

On the other hand, container.
add
Item(itemId) will return null, in case the container already contains an item with the given item id.

One other situation where I could imagine null being returned:

If your item IDs have equals() and hashCode() methods, which depend on something that can change at runtime, you might not be able to retrieve the items correctly.

Thanks for your answers, it turns out that the problem is what Henri described, my equals method doesn’t work correctly it seems.

Thanks for your help!

Yet, I don’t understand it why this fails. Let me explain:

My itemId object contains a hashCode and equals implementation that check some fields that might change at runtime (in fact they do just before I try to iterate over the itemIds).

Now using debug mode

for(Object itemId : container.getItemIds()) {

fetches the correct itemId (that already contains the changed value), let’s say its Object@1234. Looking into the container, I see the items Hashtable, containing a Hashtable$Entry8742, with key Object@1234. See the objects are not only equal they are identical, that’s why I really don’t understand why

Item item = container.getItem(itemId);

returns null for that itemId, when I clearly see that the itemId is in fact in the items Hashtable of the container.

It definitly has something to do with my equals / hashCode implementation, because that specific part works, if I use the default implementation, however I need that equals method in other parts of my application (where it is working without issues). I’m pretty sure, that it’s implementation is correct too.

Please point me in the right direction!