Java – pass a zero size array to save the allocation?
In this code example, from page 107, the last line:
Update[] updates = lu.toArray(new Update[0]);
Contains comments: pass a zero size array and save the allocation
List<Update> lu = new ArrayList<Update>(); String text = ""; final Update.Builder ub = new Update.Builder(); final Author a = new Author("Tallulah"); for (int i=0; i<256; i++) { text = text + "X"; long Now = System.currentTimeMillis(); lu.add(ub.author(a).updateText(text).createTime(Now).build()); try { Thread.sleep(1); } catch (InterruptedException e) { } } Collections.shuffle(lu); Update[] updates = lu.toArray(new Update[0]);
What is the distribution savings?
The Javadoc of list #toarray (t [] a) mentions:
This is what I remember: if the array passed to toArray (t [] a) does not fit all the contents of the list, a new array will be allocated Obviously, there are 256 elements in the list, which can't be put into an array of size 0, so a new array must be allocated inside the method, right?
Is this description incorrect? Or what does it mean?
Solution
Yes
You can use
private static final Update NO_UPDATES = { } lu.toArray(NO_UPDATES);
However, this will only help if you want the list to be usually 0 in length
Generally speaking, I will use the same method as FGE
lu.toArray(new Update[lu.size()]);
In your specific case, you know the size in advance so that you can do it
Update[] updates = new Update[256]; String text = ""; final Update.Builder ub = new Update.Builder(); final Author a = new Author("Tallulah"); long Now = System.currentTimeMillis(); for (int i=0; i<updates.length; i++) updates[i] = ub.author(a).updateText(text += 'X').createTime(Now++).build(); Collections.shuffle(Arrays.asList(updates));