ConcurrentAppendOnlyChunkedList { public T[] toArray(IntFunction<T[]> arrayAllocator) { final long lastIndex = getValidLastIndex(); assert lastIndex <= Integer.MAX_VALUE; final int size = (int) lastIndex; final T[] elements = arrayAllocator.apply(size); final int chunkSize = this.chunkSize; final int chunks = size > chunkSize ? size >> chunkSizeLog2 : 0; AtomicChunk<T> buffer = firstBuffer; int elementIndex = 0; for (int i = 0; i < chunks; i++) { drain(buffer, elements, elementIndex, chunkSize); elementIndex += chunkSize; buffer = buffer.next; } final int remaining = chunks > 0 ? (size & chunkMask) : size; drain(buffer, elements, elementIndex, remaining); return elements; } ConcurrentAppendOnlyChunkedList(final int chunkSize); int size(); void addAll(T[] elements); T get(int index); void add(T e); T[] toArray(IntFunction<T[]> arrayAllocator);  }
@Test public void shouldToArrayReturnEmptyArrayIfEmpty() { final Integer[] array = chunkedList.toArray(Integer[]::new); Assert.assertArrayEquals(new Integer[0], array); }