I am looking for a java data structure similar to an ArrayList that when I do an add or a push with only a value argument an index will be returned for me automatically.
For example:
ArrayList<String> elements = new ArrayList<String>();
String element = "foo";
String elementTwo = "bar";
int index1 = elements.add(element); //note this does not exist, i.e. returns bool in api
int index2 = elements.add(elementTwo);
System.out.println(elements.get(index1)); //would give "foo"
I could see writing a wrapper class around ArrayList that manages a counter that is incremented on every add operation and invoking:
ArrayList.add(int index, E element)
Do you really need to write a wrapper around ArrayList for this? This seems like something simple enough to be provided out of the box somewhere?
Edit:
I need the index (key) to be fixed and unique for this usecase. A map was suggested and I agree with that. Does anyone know of a map implementation that gives you an automatically (uniquely) generated key on a value insert? I am just trying to decide if I need to implement my own wrapper for this.
The element will be added at the end of the list. So you can use
elements.size()-1to get the new elements index.Note that this will not work reliable if multiple threads are modifying the list at the same time.
EDIT: Also note that it might not be a good idea to use an
ArrayLists index as a unique ID because an elements index can change (for example when you remove an element or insert a new one usingadd(int, Object)). If this is a problem depends on what you want to do with the index: If you only need it for a short time after adding an element and can be sure that the list is not modified in the meantime, there is no problem. In the other case even a method returning the index when callingadd(Object)would not help because the index does not get updated in anyway. To prevent this issue you can:add(int, Object).nullusing the methodset(int, null). This way no elements index will change.EDIT 2: I did not find a appropriate, ready to use implementation (but this does not mean there is none, of course). To suggest a good solution, more information on the intended use of the data structure is needed, but here are some ideas and notes:
ArrayListcould be used and the elements index represents the ID. As stated above, to remove an element it can be set tonullso that no indices are changed. When inserting, positions withnullvalues can be reused.AtomicLongorIdentityHashMap)Object.hashCode()orSystem.identityHashCode(Object)as it is not guaranteed (try it by running the example at the bottom of Suns/Oracles Bug #6321873).