Found an interesting thing about ArrayList,
ArrayList<String> list = new ArrayList<String>();
list.add(0, "0-element");
list.add(1, "1-element");
list.add(2, "2-element");
But if the elements are not coming in an unknown order, eg.
ArrayList<String> list = new ArrayList<String>();
list.add(1, "1-element"); // IndexOutOfBoundsException
list.add(2, "2-element");
list.add(0, "0-element");
You get IndexOutOfBoundsException, Is the only option here is to use a Map instead of List?
This is documented :
You could test before adding :
But what you do is strange (and that’s the reason why there is no method doing the test and adding/insertion). Do you really want to add at index (i.e. moving some of the previously inserted elements) ? Are you sure a standard array, allowing you to set elements at arbitrary index isn’t what you need ?