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.Arrays;
026import java.util.Collection;
027import org.checkerframework.checker.nullness.qual.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)
036@ElementTypesAreNonnullByDefault
037public final class ObjectArrays {
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 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 extends @Nullable Object> 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 {@code element} occupying
084   *     the first position, and the elements of {@code array} occupying the remaining elements.
085   */
086  public static <T extends @Nullable Object> T[] concat(@ParametricNullness T element, T[] array) {
087    T[] result = newArray(array, array.length + 1);
088    result[0] = element;
089    System.arraycopy(array, 0, result, 1, array.length);
090    return result;
091  }
092
093  /**
094   * Returns a new array that appends {@code element} to {@code array}.
095   *
096   * @param array the array of elements to prepend
097   * @param element the element to append to the end
098   * @return an array whose size is one larger than {@code array}, with the same contents as {@code
099   *     array}, plus {@code element} occupying the last position.
100   */
101  public static <T extends @Nullable Object> T[] concat(T[] array, @ParametricNullness T element) {
102    T[] result = Arrays.copyOf(array, array.length + 1);
103    result[array.length] = element;
104    return result;
105  }
106
107  /**
108   * Returns an array containing all of the elements in the specified collection; the runtime type
109   * of the returned array is that of the specified array. If the collection fits in the specified
110   * array, it is returned therein. Otherwise, a new array is allocated with the runtime type of the
111   * specified array and the size of the specified collection.
112   *
113   * <p>If the collection fits in the specified array with room to spare (i.e., the array has more
114   * elements than the collection), the element in the array immediately following the end of the
115   * collection is set to {@code null}. This is useful in determining the length of the collection
116   * <i>only</i> if the caller knows that the collection does not contain any null elements.
117   *
118   * <p>This method returns the elements in the order they are returned by the collection's
119   * iterator.
120   *
121   * <p>TODO(kevinb): support concurrently modified collections?
122   *
123   * @param c the collection for which to return an array of elements
124   * @param array the array in which to place the collection elements
125   * @throws ArrayStoreException if the runtime type of the specified array is not a supertype of
126   *     the runtime type of every element in the specified collection
127   */
128  static <T extends @Nullable Object> T[] toArrayImpl(Collection<?> c, T[] array) {
129    int size = c.size();
130    if (array.length < size) {
131      array = newArray(array, size);
132    }
133    fillArray(c, array);
134    if (array.length > size) {
135      @Nullable Object[] unsoundlyCovariantArray = array;
136      unsoundlyCovariantArray[size] = null;
137    }
138    return array;
139  }
140
141  /**
142   * Implementation of {@link Collection#toArray(Object[])} for collections backed by an object
143   * array. the runtime type of the returned array is that of the specified array. If the collection
144   * fits in the specified array, it is returned therein. Otherwise, a new array is allocated with
145   * the runtime type of the specified array and the size of the specified collection.
146   *
147   * <p>If the collection fits in the specified array with room to spare (i.e., the array has more
148   * elements than the collection), the element in the array immediately following the end of the
149   * collection is set to {@code null}. This is useful in determining the length of the collection
150   * <i>only</i> if the caller knows that the collection does not contain any null elements.
151   */
152  static <T extends @Nullable Object> T[] toArrayImpl(
153      @Nullable Object[] src, int offset, int len, T[] dst) {
154    checkPositionIndexes(offset, offset + len, src.length);
155    if (dst.length < len) {
156      dst = newArray(dst, len);
157    } else if (dst.length > len) {
158      @Nullable Object[] unsoundlyCovariantArray = dst;
159      unsoundlyCovariantArray[len] = null;
160    }
161    System.arraycopy(src, offset, dst, 0, len);
162    return dst;
163  }
164
165  /**
166   * Returns an array containing all of the elements in the specified collection. This method
167   * returns the elements in the order they are returned by the collection's iterator. The returned
168   * array is "safe" in that no references to it are maintained by the collection. The caller is
169   * thus free to modify the returned array.
170   *
171   * <p>This method assumes that the collection size doesn't change while the method is running.
172   *
173   * <p>TODO(kevinb): support concurrently modified collections?
174   *
175   * @param c the collection for which to return an array of elements
176   */
177  static @Nullable Object[] toArrayImpl(Collection<?> c) {
178    return fillArray(c, new Object[c.size()]);
179  }
180
181  /**
182   * Returns a copy of the specified subrange of the specified array that is literally an Object[],
183   * and not e.g. a {@code String[]}.
184   */
185  static @Nullable Object[] copyAsObjectArray(@Nullable Object[] elements, int offset, int length) {
186    checkPositionIndexes(offset, offset + length, elements.length);
187    if (length == 0) {
188      return new Object[0];
189    }
190    @Nullable Object[] result = new Object[length];
191    System.arraycopy(elements, offset, result, 0, length);
192    return result;
193  }
194
195  @CanIgnoreReturnValue
196  private static @Nullable Object[] fillArray(Iterable<?> elements, @Nullable Object[] array) {
197    int i = 0;
198    for (Object element : elements) {
199      array[i++] = element;
200    }
201    return array;
202  }
203
204  /** Swaps {@code array[i]} with {@code array[j]}. */
205  static void swap(Object[] array, int i, int j) {
206    Object temp = array[i];
207    array[i] = array[j];
208    array[j] = temp;
209  }
210
211  @CanIgnoreReturnValue
212  static Object[] checkElementsNotNull(Object... array) {
213    return checkElementsNotNull(array, array.length);
214  }
215
216  @CanIgnoreReturnValue
217  static Object[] checkElementsNotNull(Object[] array, int length) {
218    for (int i = 0; i < length; i++) {
219      checkElementNotNull(array[i], i);
220    }
221    return array;
222  }
223
224  // We do this instead of Preconditions.checkNotNull to save boxing and array
225  // creation cost.
226  @CanIgnoreReturnValue
227  static Object checkElementNotNull(Object element, int index) {
228    if (element == null) {
229      throw new NullPointerException("at index " + index);
230    }
231    return element;
232  }
233}