Title pretty much says it all. I had a hard time finding information on this, so I did some trial and error, and I thought I would share my results here.
Coming from a PHP background, I expected Java's ArrayList
type to support sparse indicies. For example, in PHP I can do:
$test = array(
"Item 1",
"Item 2",
"Item 3"
);
unset($test[1]);
echo $test[2];
And get "Item 3" back. But, when I try something similar in Java:
ArrayList<String> test = new ArrayList<>();
test.add("Item 1");
test.add("Item 2");
test.add("Item 3");
test.remove(1);
System.out.println(test.get(2));
I get an IndexOutOfBoundsException
. It would appear that when you remove the element, the array gets re-indexed. Maybe I'm missing something (I'm pretty new to Java), but it seems to me that if you depend on knowing an index won't change if elements are removed, you should using something like HashMap
instead of ArrayList
.