Q:

Update ArrayList index in Object

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.

A:

This it's possible using Map - HashMap
Example:
Map<Integer, MyObject> map = new HashMap<Integer, MyObject>();
MyObject obj = new MyObject();
Integer key = new Integer("1234");
obj.setKey(key);
map.put(obj.getKey(), obj);

for retrieve the object, call:
MyObject result = map.get(key);

result = null;

map.put(key, result);

Every key it's unique on the map so, if you change the value, it's dont affect the key.
In this case you can store a key with null value.
Otherwise, If you remove an index, and put it again, will solve:
        List<String> list = new ArrayList<String>();
        list.add("ONE");
        list.add("TWO");

        for (int index = 0; index < list.size(); index ++) {
            // remove the index that you will change to null
            list.remove(index);
            // put a null object in that index
            list.set(index, null);
            System.out.println(list.get(index));
        }

But I think that Map it's what you looking for. This second approach it's not thread safe and will cause crashes in case of concurrent threads

