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;
023import com.google.errorprone.annotations.CanIgnoreReturnValue;
024import java.lang.reflect.Array;
025import java.util.Collection;
026import javax.annotation.Nullable;
027
028/**
029 * Static utility methods pertaining to object arrays.
030 *
031 * @author Kevin Bourrillion
032 * @since 2.0
033 */
034@GwtCompatible(emulated = true)
035public final class ObjectArrays {
036  static final Object[] EMPTY_ARRAY = new Object[0];
037
038  private ObjectArrays() {}
039
040  /**
041   * Returns a new array of the given length with the specified component type.
042   *
043   * @param type the component type
044   * @param length the length of the new array
045   */
046  @GwtIncompatible // Array.newInstance(Class, int)
047  @SuppressWarnings("unchecked")
048  public static <T> T[] newArray(Class<T> type, int length) {
049    return (T[]) Array.newInstance(type, length);
050  }
051
052  /**
053   * Returns a new array of the given length with the same type as a reference
054   * array.
055   *
056   * @param reference any array of the desired type
057   * @param length the length of the new array
058   */
059  public static <T> T[] newArray(T[] reference, int length) {
060    return Platform.newArray(reference, length);
061  }
062
063  /**
064   * Returns a new array that contains the concatenated contents of two arrays.
065   *
066   * @param first the first array of elements to concatenate
067   * @param second the second array of elements to concatenate
068   * @param type the component type of the returned array
069   */
070  @GwtIncompatible // Array.newInstance(Class, int)
071  public static <T> T[] concat(T[] first, T[] second, Class<T> type) {
072    T[] result = newArray(type, first.length + second.length);
073    System.arraycopy(first, 0, result, 0, first.length);
074    System.arraycopy(second, 0, result, first.length, second.length);
075    return result;
076  }
077
078  /**
079   * Returns a new array that prepends {@code element} to {@code array}.
080   *
081   * @param element the element to prepend to the front of {@code array}
082   * @param array the array of elements to append
083   * @return an array whose size is one larger than {@code array}, with
084   *     {@code element} occupying the first position, and the
085   *     elements of {@code array} occupying the remaining elements.
086   */
087  public static <T> T[] concat(@Nullable T element, T[] array) {
088    T[] result = newArray(array, array.length + 1);
089    result[0] = element;
090    System.arraycopy(array, 0, result, 1, array.length);
091    return result;
092  }
093
094  /**
095   * Returns a new array that appends {@code element} to {@code array}.
096   *
097   * @param array the array of elements to prepend
098   * @param element the element to append to the end
099   * @return an array whose size is one larger than {@code array}, with
100   *     the same contents as {@code array}, plus {@code element} occupying the
101   *     last position.
102   */
103  public static <T> T[] concat(T[] array, @Nullable T element) {
104    T[] result = arraysCopyOf(array, array.length + 1);
105    result[array.length] = element;
106    return result;
107  }
108
109  /** GWT safe version of Arrays.copyOf. */
110  static <T> T[] arraysCopyOf(T[] original, int newLength) {
111    T[] copy = newArray(original, newLength);
112    System.arraycopy(original, 0, copy, 0, Math.min(original.length, newLength));
113    return copy;
114  }
115
116  /**
117   * Returns an array containing all of the elements in the specified
118   * collection; the runtime type of the returned array is that of the specified
119   * array. If the collection fits in the specified array, it is returned
120   * therein. Otherwise, a new array is allocated with the runtime type of the
121   * specified array and the size of the specified collection.
122   *
123   * <p>If the collection fits in the specified array with room to spare (i.e.,
124   * the array has more elements than the collection), the element in the array
125   * immediately following the end of the collection is set to {@code null}.
126   * This is useful in determining the length of the collection <i>only</i> if
127   * the caller knows that the collection does not contain any null elements.
128   *
129   * <p>This method returns the elements in the order they are returned by the
130   * collection's iterator.
131   *
132   * <p>TODO(kevinb): support concurrently modified collections?
133   *
134   * @param c the collection for which to return an array of elements
135   * @param array the array in which to place the collection elements
136   * @throws ArrayStoreException if the runtime type of the specified array is
137   *     not a supertype of the runtime type of every element in the specified
138   *     collection
139   */
140  static <T> T[] toArrayImpl(Collection<?> c, T[] array) {
141    int size = c.size();
142    if (array.length < size) {
143      array = newArray(array, size);
144    }
145    fillArray(c, array);
146    if (array.length > size) {
147      array[size] = null;
148    }
149    return array;
150  }
151
152  /**
153   * Implementation of {@link Collection#toArray(Object[])} for collections backed by an object
154   * array. the runtime type of the returned array is that of the specified array. If the collection
155   * fits in the specified array, it is returned therein. Otherwise, a new array is allocated with
156   * the runtime type of the specified array and the size of the specified collection.
157   *
158   * <p>If the collection fits in the specified array with room to spare (i.e., the array has more
159   * elements than the collection), the element in the array immediately following the end of the
160   * collection is set to {@code null}. This is useful in determining the length of the collection
161   * <i>only</i> if the caller knows that the collection does not contain any null elements.
162   */
163  static <T> T[] toArrayImpl(Object[] src, int offset, int len, T[] dst) {
164    checkPositionIndexes(offset, offset + len, src.length);
165    if (dst.length < len) {
166      dst = newArray(dst, len);
167    } else if (dst.length > len) {
168      dst[len] = null;
169    }
170    System.arraycopy(src, offset, dst, 0, len);
171    return dst;
172  }
173
174  /**
175   * Returns an array containing all of the elements in the specified
176   * collection. This method returns the elements in the order they are returned
177   * by the collection's iterator. The returned array is "safe" in that no
178   * references to it are maintained by the collection. The caller is thus free
179   * to modify the returned array.
180   *
181   * <p>This method assumes that the collection size doesn't change while the
182   * method is running.
183   *
184   * <p>TODO(kevinb): support concurrently modified collections?
185   *
186   * @param c the collection for which to return an array of elements
187   */
188  static Object[] toArrayImpl(Collection<?> c) {
189    return fillArray(c, new Object[c.size()]);
190  }
191
192  /**
193   * Returns a copy of the specified subrange of the specified array that is literally an Object[],
194   * and not e.g. a {@code String[]}.
195   */
196  static Object[] copyAsObjectArray(Object[] elements, int offset, int length) {
197    checkPositionIndexes(offset, offset + length, elements.length);
198    if (length == 0) {
199      return EMPTY_ARRAY;
200    }
201    Object[] result = new Object[length];
202    System.arraycopy(elements, offset, result, 0, length);
203    return result;
204  }
205
206  @CanIgnoreReturnValue
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  @CanIgnoreReturnValue
225  static Object[] checkElementsNotNull(Object... array) {
226    return checkElementsNotNull(array, array.length);
227  }
228
229  @CanIgnoreReturnValue
230  static Object[] checkElementsNotNull(Object[] array, int length) {
231    for (int i = 0; i < length; i++) {
232      checkElementNotNull(array[i], i);
233    }
234    return array;
235  }
236
237  // We do this instead of Preconditions.checkNotNull to save boxing and array
238  // creation cost.
239  @CanIgnoreReturnValue
240  static Object checkElementNotNull(Object element, int index) {
241    if (element == null) {
242      throw new NullPointerException("at index " + index);
243    }
244    return element;
245  }
246}