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