--- jsr166/src/jdk7/java/util/ArrayDeque.java 2012/12/16 20:55:09 1.1 +++ jsr166/src/jdk7/java/util/ArrayDeque.java 2013/02/20 12:27:14 1.2 @@ -133,24 +133,6 @@ public class ArrayDeque extends Abstr } /** - * Copies the elements from our element array into the specified array, - * in order (from first to last element in the deque). It is assumed - * that the array is large enough to hold all elements in the deque. - * - * @return its argument - */ - private T[] copyElements(T[] a) { - if (head < tail) { - System.arraycopy(elements, head, a, 0, size()); - } else if (head > tail) { - int headPortionLen = elements.length - head; - System.arraycopy(elements, head, a, 0, headPortionLen); - System.arraycopy(elements, 0, a, headPortionLen, tail); - } - return a; - } - - /** * Constructs an empty array deque with an initial capacity * sufficient to hold 16 elements. */ @@ -735,7 +717,14 @@ public class ArrayDeque extends Abstr * @return an array containing all of the elements in this deque */ public Object[] toArray() { - return copyElements(new Object[size()]); + final int head = this.head; + final int tail = this.tail; + boolean wrap = (tail < head); + int end = wrap ? tail + elements.length : tail; + Object[] a = Arrays.copyOfRange(elements, head, end); + if (wrap) + System.arraycopy(elements, 0, a, elements.length - head, tail); + return a; } /** @@ -776,13 +765,22 @@ public class ArrayDeque extends Abstr */ @SuppressWarnings("unchecked") public T[] toArray(T[] a) { - int size = size(); - if (a.length < size) - a = (T[])java.lang.reflect.Array.newInstance( - a.getClass().getComponentType(), size); - copyElements(a); - if (a.length > size) - a[size] = null; + final int head = this.head; + final int tail = this.tail; + boolean wrap = (tail < head); + int size = (tail - head) + (wrap ? elements.length : 0); + int firstLeg = size - (wrap ? tail : 0); + int len = a.length; + if (size > len) { + a = (T[]) Arrays.copyOfRange(elements, head, head + size, + a.getClass()); + } else { + System.arraycopy(elements, head, a, 0, firstLeg); + if (size < len) + a[size] = null; + } + if (wrap) + System.arraycopy(elements, 0, a, firstLeg, tail); return a; }