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