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