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