Wondering whether there is an efficient way to add an item to Java's ArrayList at a bigger position than its current size:
Scenario:
ArrayList<Item> items = new ArrayList<Item>;
... let's say I add three elements
Now I would like to add an item at position 10 (leaving items from 3 to 10 to null)
items.add(10,newItem); // item.size() == 3
Is there an efficient way resizing/filling an ArrayList with nulls?
Java's implementation makes size field private :-(..
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With