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