I have an ArrayList with a bunch of MyObject objects. I want to keep an integer field in my object that is the key of this object in the ArrayList, so that I can easy get the position of this element in the ArrayList.
This gets a problem when I remove one object from this ArrayList, because the indexes get shifted to the left. What is the best way to avoid this problem?
Should I not remove the elements, but override them with null (so that the index gets not shifted) or should I rather iterate through the ArrayList after one removal to update all ID fields in the objects?
//EDIT: My purpose: Lets say I get some objects of that ArrayList and insert them in another list. Later when iterating through that second list, I want to get the key of the objects in the first ArrayList. So I must save the key at the object. Where are the benefits when using a Map in that case? The keys are only auto-increment integers.