Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java ArrayList add item outside current size

Tags:

java

arraylist

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 :-(..

like image 751
ic3 Avatar asked Jan 19 '12 11:01

ic3


2 Answers

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

like image 124
Hachi Avatar answered Sep 23 '22 09:09

Hachi


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]
like image 38
Ishtar Avatar answered Sep 20 '22 09:09

Ishtar