Java ArrayList add item outside current size
imho the best thing you can do is items.addAll(Collections.nCopies(6, null))
and hope, that ArrayList implements some behaviour to internally fasten this up
How about this?
ArrayList<Item> items = new ArrayList<Item>();
items.add(new Item(0));
items.add(new Item(1));
items.add(new Item(2));
items.addAll(Collections.<Item>nCopies(7, null));
items.add(10,new Item(10));
System.out.println(items);
prints
[0, 1, 2, null, null, null, null, null, null, null, 10]
This is an older question, but you can now use SparseArray
as an (almost) direct drop-in replacement for ArrayList
. It allows non-contiguous integer key values, and returns null if a value has not been set for a key. Performance-wise it was designed exactly for your needs. Instead of add
you use append
, which is more descriptive in that you are appending to the end of whatever the max key is, even if there is gaps. You can also set
at any key value you'd like, even if it is beyond the maximum key.