001/*
002 * Copyright (C) 2007 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package com.google.common.collect;
018
019import static com.google.common.base.Preconditions.checkPositionIndexes;
020
021import com.google.common.annotations.GwtCompatible;
022import com.google.common.annotations.GwtIncompatible;
023
024import java.lang.reflect.Array;
025import java.util.Collection;
026
027import javax.annotation.Nullable;
028
029/**
030 * Static utility methods pertaining to object arrays.
031 *
032 * @author Kevin Bourrillion
033 * @since 2.0
034 */
035@GwtCompatible(emulated = true)
036public final class ObjectArrays {
037  static final Object[] EMPTY_ARRAY = new Object[0];
038
039  private ObjectArrays() {}
040
041  /**
042   * Returns a new array of the given length with the specified component type.
043   *
044   * @param type the component type
045   * @param length the length of the new array
046   */
047  @GwtIncompatible("Array.newInstance(Class, int)")
048  @SuppressWarnings("unchecked")
049  public static <T> T[] newArray(Class<T> type, int length) {
050    return (T[]) Array.newInstance(type, length);
051  }
052
053  /**
054   * Returns a new array of the given length with the same type as a reference
055   * array.
056   *
057   * @param reference any array of the desired type
058   * @param length the length of the new array
059   */
060  public static <T> T[] newArray(T[] reference, int length) {
061    return Platform.newArray(reference, length);
062  }
063
064  /**
065   * Returns a new array that contains the concatenated contents of two arrays.
066   *
067   * @param first the first array of elements to concatenate
068   * @param second the second array of elements to concatenate
069   * @param type the component type of the returned array
070   */
071  @GwtIncompatible("Array.newInstance(Class, int)")
072  public static <T> T[] concat(T[] first, T[] second, Class<T> type) {
073    T[] result = newArray(type, first.length + second.length);
074    System.arraycopy(first, 0, result, 0, first.length);
075    System.arraycopy(second, 0, result, first.length, second.length);
076    return result;
077  }
078
079  /**
080   * Returns a new array that prepends {@code element} to {@code array}.
081   *
082   * @param element the element to prepend to the front of {@code array}
083   * @param array the array of elements to append
084   * @return an array whose size is one larger than {@code array}, with
085   *     {@code element} occupying the first position, and the
086   *     elements of {@code array} occupying the remaining elements.
087   */
088  public static <T> T[] concat(@Nullable T element, T[] array) {
089    T[] result = newArray(array, array.length + 1);
090    result[0] = element;
091    System.arraycopy(array, 0, result, 1, array.length);
092    return result;
093  }
094
095  /**
096   * Returns a new array that appends {@code element} to {@code array}.
097   *
098   * @param array the array of elements to prepend
099   * @param element the element to append to the end
100   * @return an array whose size is one larger than {@code array}, with
101   *     the same contents as {@code array}, plus {@code element} occupying the
102   *     last position.
103   */
104  public static <T> T[] concat(T[] array, @Nullable T element) {
105    T[] result = arraysCopyOf(array, array.length + 1);
106    result[array.length] = element;
107    return result;
108  }
109
110  /** GWT safe version of Arrays.copyOf. */
111  static <T> T[] arraysCopyOf(T[] original, int newLength) {
112    T[] copy = newArray(original, newLength);
113    System.arraycopy(original, 0, copy, 0, Math.min(original.length, newLength));
114    return copy;
115  }
116
117  /**
118   * Returns an array containing all of the elements in the specified
119   * collection; the runtime type of the returned array is that of the specified
120   * array. If the collection fits in the specified array, it is returned
121   * therein. Otherwise, a new array is allocated with the runtime type of the
122   * specified array and the size of the specified collection.
123   *
124   * <p>If the collection fits in the specified array with room to spare (i.e.,
125   * the array has more elements than the collection), the element in the array
126   * immediately following the end of the collection is set to {@code null}.
127   * This is useful in determining the length of the collection <i>only</i> if
128   * the caller knows that the collection does not contain any null elements.
129   *
130   * <p>This method returns the elements in the order they are returned by the
131   * collection's iterator.
132   *
133   * <p>TODO(kevinb): support concurrently modified collections?
134   *
135   * @param c the collection for which to return an array of elements
136   * @param array the array in which to place the collection elements
137   * @throws ArrayStoreException if the runtime type of the specified array is
138   *     not a supertype of the runtime type of every element in the specified
139   *     collection
140   */
141  static <T> T[] toArrayImpl(Collection<?> c, T[] array) {
142    int size = c.size();
143    if (array.length < size) {
144      array = newArray(array, size);
145    }
146    fillArray(c, array);
147    if (array.length > size) {
148      array[size] = null;
149    }
150    return array;
151  }
152
153  /**
154   * Implementation of {@link Collection#toArray(Object[])} for collections backed by an object
155   * array. the runtime type of the returned array is that of the specified array. If the collection
156   * fits in the specified array, it is returned therein. Otherwise, a new array is allocated with
157   * the runtime type of the specified array and the size of the specified collection.
158   *
159   * <p>If the collection fits in the specified array with room to spare (i.e., the array has more
160   * elements than the collection), the element in the array immediately following the end of the
161   * collection is set to {@code null}. This is useful in determining the length of the collection
162   * <i>only</i> if the caller knows that the collection does not contain any null elements.
163   */
164  static <T> T[] toArrayImpl(Object[] src, int offset, int len, T[] dst) {
165    checkPositionIndexes(offset, offset + len, src.length);
166    if (dst.length < len) {
167      dst = newArray(dst, len);
168    } else if (dst.length > len) {
169      dst[len] = null;
170    }
171    System.arraycopy(src, offset, dst, 0, len);
172    return dst;
173  }
174
175  /**
176   * Returns an array containing all of the elements in the specified
177   * collection. This method returns the elements in the order they are returned
178   * by the collection's iterator. The returned array is "safe" in that no
179   * references to it are maintained by the collection. The caller is thus free
180   * to modify the returned array.
181   *
182   * <p>This method assumes that the collection size doesn't change while the
183   * method is running.
184   *
185   * <p>TODO(kevinb): support concurrently modified collections?
186   *
187   * @param c the collection for which to return an array of elements
188   */
189  static Object[] toArrayImpl(Collection<?> c) {
190    return fillArray(c, new Object[c.size()]);
191  }
192
193  /**
194   * Returns a copy of the specified subrange of the specified array that is literally an Object[],
195   * and not e.g. a {@code String[]}.
196   */
197  static Object[] copyAsObjectArray(Object[] elements, int offset, int length) {
198    checkPositionIndexes(offset, offset + length, elements.length);
199    if (length == 0) {
200      return EMPTY_ARRAY;
201    }
202    Object[] result = new Object[length];
203    System.arraycopy(elements, offset, result, 0, length);
204    return result;
205  }
206
207  private static Object[] fillArray(Iterable<?> elements, Object[] array) {
208    int i = 0;
209    for (Object element : elements) {
210      array[i++] = element;
211    }
212    return array;
213  }
214
215  /**
216   * Swaps {@code array[i]} with {@code array[j]}.
217   */
218  static void swap(Object[] array, int i, int j) {
219    Object temp = array[i];
220    array[i] = array[j];
221    array[j] = temp;
222  }
223
224  static Object[] checkElementsNotNull(Object... array) {
225    return checkElementsNotNull(array, array.length);
226  }
227
228  static Object[] checkElementsNotNull(Object[] array, int length) {
229    for (int i = 0; i < length; i++) {
230      checkElementNotNull(array[i], i);
231    }
232    return array;
233  }
234
235  // We do this instead of Preconditions.checkNotNull to save boxing and array
236  // creation cost.
237  static Object checkElementNotNull(Object element, int index) {
238    if (element == null) {
239      throw new NullPointerException("at index " + index);
240    }
241    return element;
242  }
243}