001/* 002 * Copyright (C) 2008 The Guava Authors 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 005 * in compliance with the License. You may obtain a copy of the License at 006 * 007 * http://www.apache.org/licenses/LICENSE-2.0 008 * 009 * Unless required by applicable law or agreed to in writing, software distributed under the License 010 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 011 * or implied. See the License for the specific language governing permissions and limitations under 012 * the License. 013 */ 014 015package com.google.common.primitives; 016 017import static com.google.common.base.Preconditions.checkArgument; 018import static com.google.common.base.Preconditions.checkElementIndex; 019import static com.google.common.base.Preconditions.checkNotNull; 020import static com.google.common.base.Preconditions.checkPositionIndexes; 021import static java.lang.Math.floorMod; 022import static java.lang.System.arraycopy; 023import static java.util.Arrays.sort; 024import static java.util.Collections.emptyList; 025 026import com.google.common.annotations.GwtCompatible; 027import com.google.common.annotations.GwtIncompatible; 028import com.google.common.annotations.J2ktIncompatible; 029import com.google.common.base.Converter; 030import com.google.errorprone.annotations.InlineMe; 031import com.google.errorprone.annotations.InlineMeValidationDisabled; 032import java.io.Serializable; 033import java.util.AbstractList; 034import java.util.Arrays; 035import java.util.Collection; 036import java.util.Comparator; 037import java.util.List; 038import java.util.RandomAccess; 039import java.util.Spliterator; 040import java.util.Spliterators; 041import org.jspecify.annotations.Nullable; 042 043/** 044 * Static utility methods pertaining to {@code int} primitives, that are not already found in either 045 * {@link Integer} or {@link Arrays}. 046 * 047 * <p>See the Guava User Guide article on <a 048 * href="https://github.com/google/guava/wiki/PrimitivesExplained">primitive utilities</a>. 049 * 050 * @author Kevin Bourrillion 051 * @since 1.0 052 */ 053@GwtCompatible 054public final class Ints extends IntsMethodsForWeb { 055 private Ints() {} 056 057 /** 058 * The number of bytes required to represent a primitive {@code int} value. 059 * 060 * <p>Prefer {@link Integer#BYTES} instead. 061 */ 062 public static final int BYTES = Integer.BYTES; 063 064 /** 065 * The largest power of two that can be represented as an {@code int}. 066 * 067 * @since 10.0 068 */ 069 public static final int MAX_POWER_OF_TWO = 1 << (Integer.SIZE - 2); 070 071 /** 072 * Returns a hash code for {@code value}; obsolete alternative to {@link Integer#hashCode(int)}. 073 * 074 * @param value a primitive {@code int} value 075 * @return a hash code for the value 076 */ 077 @InlineMe(replacement = "Integer.hashCode(value)") 078 @InlineMeValidationDisabled( 079 "The hash code of an int is the int itself, so it's simplest to return that.") 080 public static int hashCode(int value) { 081 return value; 082 } 083 084 /** 085 * Returns the {@code int} value that is equal to {@code value}, if possible. 086 * 087 * <p><b>Note:</b> this method is now unnecessary and should be treated as deprecated. Use {@link 088 * Math#toIntExact(long)} instead, but be aware that that method throws {@link 089 * ArithmeticException} rather than {@link IllegalArgumentException}. 090 * 091 * @param value any value in the range of the {@code int} type 092 * @return the {@code int} value that equals {@code value} 093 * @throws IllegalArgumentException if {@code value} is greater than {@link Integer#MAX_VALUE} or 094 * less than {@link Integer#MIN_VALUE} 095 */ 096 public static int checkedCast(long value) { 097 int result = (int) value; 098 checkArgument(result == value, "Out of range: %s", value); 099 return result; 100 } 101 102 /** 103 * Returns the {@code int} nearest in value to {@code value}. 104 * 105 * @param value any {@code long} value 106 * @return the same value cast to {@code int} if it is in the range of the {@code int} type, 107 * {@link Integer#MAX_VALUE} if it is too large, or {@link Integer#MIN_VALUE} if it is too 108 * small 109 */ 110 public static int saturatedCast(long value) { 111 if (value > Integer.MAX_VALUE) { 112 return Integer.MAX_VALUE; 113 } 114 if (value < Integer.MIN_VALUE) { 115 return Integer.MIN_VALUE; 116 } 117 return (int) value; 118 } 119 120 /** 121 * Compares the two specified {@code int} values. The sign of the value returned is the same as 122 * that of {@code ((Integer) a).compareTo(b)}. 123 * 124 * <p><b>Note:</b> this method is now unnecessary and should be treated as deprecated; use the 125 * equivalent {@link Integer#compare} method instead. 126 * 127 * @param a the first {@code int} to compare 128 * @param b the second {@code int} to compare 129 * @return a negative value if {@code a} is less than {@code b}; a positive value if {@code a} is 130 * greater than {@code b}; or zero if they are equal 131 */ 132 @InlineMe(replacement = "Integer.compare(a, b)") 133 public static int compare(int a, int b) { 134 return Integer.compare(a, b); 135 } 136 137 /** 138 * Returns {@code true} if {@code target} is present as an element anywhere in {@code array}. 139 * 140 * @param array an array of {@code int} values, possibly empty 141 * @param target a primitive {@code int} value 142 * @return {@code true} if {@code array[i] == target} for some value of {@code i} 143 */ 144 public static boolean contains(int[] array, int target) { 145 for (int value : array) { 146 if (value == target) { 147 return true; 148 } 149 } 150 return false; 151 } 152 153 /** 154 * Returns the index of the first appearance of the value {@code target} in {@code array}. 155 * 156 * @param array an array of {@code int} values, possibly empty 157 * @param target a primitive {@code int} value 158 * @return the least index {@code i} for which {@code array[i] == target}, or {@code -1} if no 159 * such index exists. 160 */ 161 public static int indexOf(int[] array, int target) { 162 return indexOf(array, target, 0, array.length); 163 } 164 165 // TODO(kevinb): consider making this public 166 private static int indexOf(int[] array, int target, int start, int end) { 167 for (int i = start; i < end; i++) { 168 if (array[i] == target) { 169 return i; 170 } 171 } 172 return -1; 173 } 174 175 /** 176 * Returns the start position of the first occurrence of the specified {@code target} within 177 * {@code array}, or {@code -1} if there is no such occurrence. 178 * 179 * <p>More formally, returns the lowest index {@code i} such that {@code Arrays.copyOfRange(array, 180 * i, i + target.length)} contains exactly the same elements as {@code target}. 181 * 182 * @param array the array to search for the sequence {@code target} 183 * @param target the array to search for as a sub-sequence of {@code array} 184 */ 185 public static int indexOf(int[] array, int[] target) { 186 checkNotNull(array, "array"); 187 checkNotNull(target, "target"); 188 if (target.length == 0) { 189 return 0; 190 } 191 192 outer: 193 for (int i = 0; i < array.length - target.length + 1; i++) { 194 for (int j = 0; j < target.length; j++) { 195 if (array[i + j] != target[j]) { 196 continue outer; 197 } 198 } 199 return i; 200 } 201 return -1; 202 } 203 204 /** 205 * Returns the index of the last appearance of the value {@code target} in {@code array}. 206 * 207 * @param array an array of {@code int} values, possibly empty 208 * @param target a primitive {@code int} value 209 * @return the greatest index {@code i} for which {@code array[i] == target}, or {@code -1} if no 210 * such index exists. 211 */ 212 public static int lastIndexOf(int[] array, int target) { 213 return lastIndexOf(array, target, 0, array.length); 214 } 215 216 // TODO(kevinb): consider making this public 217 private static int lastIndexOf(int[] array, int target, int start, int end) { 218 for (int i = end - 1; i >= start; i--) { 219 if (array[i] == target) { 220 return i; 221 } 222 } 223 return -1; 224 } 225 226 /** 227 * Returns the least value present in {@code array}. 228 * 229 * @param array a <i>nonempty</i> array of {@code int} values 230 * @return the value present in {@code array} that is less than or equal to every other value in 231 * the array 232 * @throws IllegalArgumentException if {@code array} is empty 233 */ 234 @GwtIncompatible( 235 "Available in GWT! Annotation is to avoid conflict with GWT specialization of base class.") 236 public static int min(int... array) { 237 checkArgument(array.length > 0); 238 int min = array[0]; 239 for (int i = 1; i < array.length; i++) { 240 if (array[i] < min) { 241 min = array[i]; 242 } 243 } 244 return min; 245 } 246 247 /** 248 * Returns the greatest value present in {@code array}. 249 * 250 * @param array a <i>nonempty</i> array of {@code int} values 251 * @return the value present in {@code array} that is greater than or equal to every other value 252 * in the array 253 * @throws IllegalArgumentException if {@code array} is empty 254 */ 255 @GwtIncompatible( 256 "Available in GWT! Annotation is to avoid conflict with GWT specialization of base class.") 257 public static int max(int... array) { 258 checkArgument(array.length > 0); 259 int max = array[0]; 260 for (int i = 1; i < array.length; i++) { 261 if (array[i] > max) { 262 max = array[i]; 263 } 264 } 265 return max; 266 } 267 268 /** 269 * Returns the value nearest to {@code value} which is within the closed range {@code [min..max]}. 270 * 271 * <p>If {@code value} is within the range {@code [min..max]}, {@code value} is returned 272 * unchanged. If {@code value} is less than {@code min}, {@code min} is returned, and if {@code 273 * value} is greater than {@code max}, {@code max} is returned. 274 * 275 * <p><b>Java 21+ users:</b> Use {@link Math#clamp(long, int, int)} instead. Note that that method 276 * is capable of constraining a {@code long} input to an {@code int} range. 277 * 278 * @param value the {@code int} value to constrain 279 * @param min the lower bound (inclusive) of the range to constrain {@code value} to 280 * @param max the upper bound (inclusive) of the range to constrain {@code value} to 281 * @throws IllegalArgumentException if {@code min > max} 282 * @since 21.0 283 */ 284 public static int constrainToRange(int value, int min, int max) { 285 checkArgument(min <= max, "min (%s) must be less than or equal to max (%s)", min, max); 286 return Math.min(Math.max(value, min), max); 287 } 288 289 /** 290 * Returns the values from each provided array combined into a single array. For example, {@code 291 * concat(new int[] {a, b}, new int[] {}, new int[] {c}} returns the array {@code {a, b, c}}. 292 * 293 * @param arrays zero or more {@code int} arrays 294 * @return a single array containing all the values from the source arrays, in order 295 * @throws IllegalArgumentException if the total number of elements in {@code arrays} does not fit 296 * in an {@code int} 297 */ 298 public static int[] concat(int[]... arrays) { 299 long length = 0; 300 for (int[] array : arrays) { 301 length += array.length; 302 } 303 int[] result = new int[checkNoOverflow(length)]; 304 int pos = 0; 305 for (int[] array : arrays) { 306 arraycopy(array, 0, result, pos, array.length); 307 pos += array.length; 308 } 309 return result; 310 } 311 312 private static int checkNoOverflow(long result) { 313 checkArgument( 314 result == (int) result, 315 "the total number of elements (%s) in the arrays must fit in an int", 316 result); 317 return (int) result; 318 } 319 320 /** 321 * Returns a big-endian representation of {@code value} in a 4-element byte array; equivalent to 322 * {@code ByteBuffer.allocate(4).putInt(value).array()}. For example, the input value {@code 323 * 0x12131415} would yield the byte array {@code {0x12, 0x13, 0x14, 0x15}}. 324 * 325 * <p>If you need to convert and concatenate several values (possibly even of different types), 326 * use a shared {@link java.nio.ByteBuffer} instance, or use {@link 327 * com.google.common.io.ByteStreams#newDataOutput()} to get a growable buffer. 328 */ 329 public static byte[] toByteArray(int value) { 330 return new byte[] { 331 (byte) (value >> 24), (byte) (value >> 16), (byte) (value >> 8), (byte) value 332 }; 333 } 334 335 /** 336 * Returns the {@code int} value whose big-endian representation is stored in the first 4 bytes of 337 * {@code bytes}; equivalent to {@code ByteBuffer.wrap(bytes).getInt()}. For example, the input 338 * byte array {@code {0x12, 0x13, 0x14, 0x15, 0x33}} would yield the {@code int} value {@code 339 * 0x12131415}. 340 * 341 * <p>Arguably, it's preferable to use {@link java.nio.ByteBuffer}; that library exposes much more 342 * flexibility at little cost in readability. 343 * 344 * @throws IllegalArgumentException if {@code bytes} has fewer than 4 elements 345 */ 346 public static int fromByteArray(byte[] bytes) { 347 checkArgument(bytes.length >= BYTES, "array too small: %s < %s", bytes.length, BYTES); 348 return fromBytes(bytes[0], bytes[1], bytes[2], bytes[3]); 349 } 350 351 /** 352 * Returns the {@code int} value whose byte representation is the given 4 bytes, in big-endian 353 * order; equivalent to {@code Ints.fromByteArray(new byte[] {b1, b2, b3, b4})}. 354 * 355 * @since 7.0 356 */ 357 public static int fromBytes(byte b1, byte b2, byte b3, byte b4) { 358 return b1 << 24 | (b2 & 0xFF) << 16 | (b3 & 0xFF) << 8 | (b4 & 0xFF); 359 } 360 361 private static final class IntConverter extends Converter<String, Integer> 362 implements Serializable { 363 static final Converter<String, Integer> INSTANCE = new IntConverter(); 364 365 @Override 366 protected Integer doForward(String value) { 367 return Integer.decode(value); 368 } 369 370 @Override 371 protected String doBackward(Integer value) { 372 return value.toString(); 373 } 374 375 @Override 376 public String toString() { 377 return "Ints.stringConverter()"; 378 } 379 380 private Object readResolve() { 381 return INSTANCE; 382 } 383 384 @GwtIncompatible @J2ktIncompatible private static final long serialVersionUID = 1; 385 } 386 387 /** 388 * Returns a serializable converter object that converts between strings and integers using {@link 389 * Integer#decode} and {@link Integer#toString()}. The returned converter throws {@link 390 * NumberFormatException} if the input string is invalid. 391 * 392 * <p><b>Warning:</b> please see {@link Integer#decode} to understand exactly how strings are 393 * parsed. For example, the string {@code "0123"} is treated as <i>octal</i> and converted to the 394 * value {@code 83}. 395 * 396 * @since 16.0 397 */ 398 public static Converter<String, Integer> stringConverter() { 399 return IntConverter.INSTANCE; 400 } 401 402 /** 403 * Returns an array containing the same values as {@code array}, but guaranteed to be of a 404 * specified minimum length. If {@code array} already has a length of at least {@code minLength}, 405 * it is returned directly. Otherwise, a new array of size {@code minLength + padding} is 406 * returned, containing the values of {@code array}, and zeroes in the remaining places. 407 * 408 * @param array the source array 409 * @param minLength the minimum length the returned array must guarantee 410 * @param padding an extra amount to "grow" the array by if growth is necessary 411 * @throws IllegalArgumentException if {@code minLength} or {@code padding} is negative 412 * @return an array containing the values of {@code array}, with guaranteed minimum length {@code 413 * minLength} 414 */ 415 public static int[] ensureCapacity(int[] array, int minLength, int padding) { 416 checkArgument(minLength >= 0, "Invalid minLength: %s", minLength); 417 checkArgument(padding >= 0, "Invalid padding: %s", padding); 418 return (array.length < minLength) ? Arrays.copyOf(array, minLength + padding) : array; 419 } 420 421 /** 422 * Returns a string containing the supplied {@code int} values separated by {@code separator}. For 423 * example, {@code join("-", 1, 2, 3)} returns the string {@code "1-2-3"}. 424 * 425 * @param separator the text that should appear between consecutive values in the resulting string 426 * (but not at the start or end) 427 * @param array an array of {@code int} values, possibly empty 428 */ 429 public static String join(String separator, int... array) { 430 checkNotNull(separator); 431 if (array.length == 0) { 432 return ""; 433 } 434 435 // For pre-sizing a builder, just get the right order of magnitude 436 StringBuilder builder = new StringBuilder(array.length * 5); 437 builder.append(array[0]); 438 for (int i = 1; i < array.length; i++) { 439 builder.append(separator).append(array[i]); 440 } 441 return builder.toString(); 442 } 443 444 /** 445 * Returns a comparator that compares two {@code int} arrays <a 446 * href="http://en.wikipedia.org/wiki/Lexicographical_order">lexicographically</a>. That is, it 447 * compares, using {@link #compare(int, int)}), the first pair of values that follow any common 448 * prefix, or when one array is a prefix of the other, treats the shorter array as the lesser. For 449 * example, {@code [] < [1] < [1, 2] < [2]}. 450 * 451 * <p>The returned comparator is inconsistent with {@link Object#equals(Object)} (since arrays 452 * support only identity equality), but it is consistent with {@link Arrays#equals(int[], int[])}. 453 * 454 * @since 2.0 455 */ 456 public static Comparator<int[]> lexicographicalComparator() { 457 return LexicographicalComparator.INSTANCE; 458 } 459 460 private enum LexicographicalComparator implements Comparator<int[]> { 461 INSTANCE; 462 463 @Override 464 public int compare(int[] left, int[] right) { 465 int minLength = Math.min(left.length, right.length); 466 for (int i = 0; i < minLength; i++) { 467 int result = Integer.compare(left[i], right[i]); 468 if (result != 0) { 469 return result; 470 } 471 } 472 return left.length - right.length; 473 } 474 475 @Override 476 public String toString() { 477 return "Ints.lexicographicalComparator()"; 478 } 479 } 480 481 /** 482 * Sorts the elements of {@code array} in descending order. 483 * 484 * @since 23.1 485 */ 486 public static void sortDescending(int[] array) { 487 checkNotNull(array); 488 sortDescending(array, 0, array.length); 489 } 490 491 /** 492 * Sorts the elements of {@code array} between {@code fromIndex} inclusive and {@code toIndex} 493 * exclusive in descending order. 494 * 495 * @since 23.1 496 */ 497 public static void sortDescending(int[] array, int fromIndex, int toIndex) { 498 checkNotNull(array); 499 checkPositionIndexes(fromIndex, toIndex, array.length); 500 sort(array, fromIndex, toIndex); 501 reverse(array, fromIndex, toIndex); 502 } 503 504 /** 505 * Reverses the elements of {@code array}. This is equivalent to {@code 506 * Collections.reverse(Ints.asList(array))}, but is likely to be more efficient. 507 * 508 * @since 23.1 509 */ 510 public static void reverse(int[] array) { 511 checkNotNull(array); 512 reverse(array, 0, array.length); 513 } 514 515 /** 516 * Reverses the elements of {@code array} between {@code fromIndex} inclusive and {@code toIndex} 517 * exclusive. This is equivalent to {@code 518 * Collections.reverse(Ints.asList(array).subList(fromIndex, toIndex))}, but is likely to be more 519 * efficient. 520 * 521 * @throws IndexOutOfBoundsException if {@code fromIndex < 0}, {@code toIndex > array.length}, or 522 * {@code toIndex > fromIndex} 523 * @since 23.1 524 */ 525 public static void reverse(int[] array, int fromIndex, int toIndex) { 526 checkNotNull(array); 527 checkPositionIndexes(fromIndex, toIndex, array.length); 528 for (int i = fromIndex, j = toIndex - 1; i < j; i++, j--) { 529 int tmp = array[i]; 530 array[i] = array[j]; 531 array[j] = tmp; 532 } 533 } 534 535 /** 536 * Performs a right rotation of {@code array} of "distance" places, so that the first element is 537 * moved to index "distance", and the element at index {@code i} ends up at index {@code (distance 538 * + i) mod array.length}. This is equivalent to {@code Collections.rotate(Ints.asList(array), 539 * distance)}, but is considerably faster and avoids allocation and garbage collection. 540 * 541 * <p>The provided "distance" may be negative, which will rotate left. 542 * 543 * @since 32.0.0 544 */ 545 public static void rotate(int[] array, int distance) { 546 rotate(array, distance, 0, array.length); 547 } 548 549 /** 550 * Performs a right rotation of {@code array} between {@code fromIndex} inclusive and {@code 551 * toIndex} exclusive. This is equivalent to {@code 552 * Collections.rotate(Ints.asList(array).subList(fromIndex, toIndex), distance)}, but is 553 * considerably faster and avoids allocations and garbage collection. 554 * 555 * <p>The provided "distance" may be negative, which will rotate left. 556 * 557 * @throws IndexOutOfBoundsException if {@code fromIndex < 0}, {@code toIndex > array.length}, or 558 * {@code toIndex > fromIndex} 559 * @since 32.0.0 560 */ 561 public static void rotate(int[] array, int distance, int fromIndex, int toIndex) { 562 // There are several well-known algorithms for rotating part of an array (or, equivalently, 563 // exchanging two blocks of memory). This classic text by Gries and Mills mentions several: 564 // https://ecommons.cornell.edu/bitstream/handle/1813/6292/81-452.pdf. 565 // (1) "Reversal", the one we have here. 566 // (2) "Dolphin". If we're rotating an array a of size n by a distance of d, then element a[0] 567 // ends up at a[d], which in turn ends up at a[2d], and so on until we get back to a[0]. 568 // (All indices taken mod n.) If d and n are mutually prime, all elements will have been 569 // moved at that point. Otherwise, we can rotate the cycle a[1], a[1 + d], a[1 + 2d], etc, 570 // then a[2] etc, and so on until we have rotated all elements. There are gcd(d, n) cycles 571 // in all. 572 // (3) "Successive". We can consider that we are exchanging a block of size d (a[0..d-1]) with a 573 // block of size n-d (a[d..n-1]), where in general these blocks have different sizes. If we 574 // imagine a line separating the first block from the second, we can proceed by exchanging 575 // the smaller of these blocks with the far end of the other one. That leaves us with a 576 // smaller version of the same problem. 577 // Say we are rotating abcdefgh by 5. We start with abcde|fgh. The smaller block is [fgh]: 578 // [abc]de|[fgh] -> [fgh]de|[abc]. Now [fgh] is in the right place, but we need to swap [de] 579 // with [abc]: fgh[de]|a[bc] -> fgh[bc]|a[de]. Now we need to swap [a] with [bc]: 580 // fgh[b]c|[a]de -> fgh[a]c|[b]de. Finally we need to swap [c] with [b]: 581 // fgha[c]|[b]de -> fgha[b]|[c]de. Because these two blocks are the same size, we are done. 582 // The Dolphin algorithm is attractive because it does the fewest array reads and writes: each 583 // array slot is read and written exactly once. However, it can have very poor memory locality: 584 // benchmarking shows it can take 7 times longer than the other two in some cases. The other two 585 // do n swaps, minus a delta (0 or 2 for Reversal, gcd(d, n) for Successive), so that's about 586 // twice as many reads and writes. But benchmarking shows that they usually perform better than 587 // Dolphin. Reversal is about as good as Successive on average, and it is much simpler, 588 // especially since we already have a `reverse` method. 589 checkNotNull(array); 590 checkPositionIndexes(fromIndex, toIndex, array.length); 591 int length = toIndex - fromIndex; 592 if (length <= 1) { 593 return; 594 } 595 596 // Map the given distance to an equivalent, non-negative value less than "length". 597 distance = floorMod(distance, length); 598 if (distance == 0) { 599 return; 600 } 601 // The current index of what will become the first element of the rotated section. 602 int newFirstIndex = toIndex - distance; 603 604 reverse(array, fromIndex, newFirstIndex); 605 reverse(array, newFirstIndex, toIndex); 606 reverse(array, fromIndex, toIndex); 607 } 608 609 /** 610 * Returns an array containing each value of {@code collection}, converted to a {@code int} value 611 * in the manner of {@link Number#intValue}. 612 * 613 * <p>Elements are copied from the argument collection as if by {@code collection.toArray()}. 614 * Calling this method is as thread-safe as calling that method. 615 * 616 * @param collection a collection of {@code Number} instances 617 * @return an array containing the same values as {@code collection}, in the same order, converted 618 * to primitives 619 * @throws NullPointerException if {@code collection} or any of its elements is null 620 * @since 1.0 (parameter was {@code Collection<Integer>} before 12.0) 621 */ 622 public static int[] toArray(Collection<? extends Number> collection) { 623 if (collection instanceof IntArrayAsList) { 624 return ((IntArrayAsList) collection).toIntArray(); 625 } 626 627 Object[] boxedArray = collection.toArray(); 628 int len = boxedArray.length; 629 int[] array = new int[len]; 630 for (int i = 0; i < len; i++) { 631 // checkNotNull for GWT (do not optimize) 632 array[i] = ((Number) checkNotNull(boxedArray[i])).intValue(); 633 } 634 return array; 635 } 636 637 /** 638 * Returns a fixed-size list backed by the specified array, similar to {@link 639 * Arrays#asList(Object[])}. The list supports {@link List#set(int, Object)}, but any attempt to 640 * set a value to {@code null} will result in a {@link NullPointerException}. 641 * 642 * <p>The returned list maintains the values, but not the identities, of {@code Integer} objects 643 * written to or read from it. For example, whether {@code list.get(0) == list.get(0)} is true for 644 * the returned list is unspecified. 645 * 646 * <p>The returned list is serializable. 647 * 648 * <p><b>Note:</b> when possible, you should represent your data as an {@link ImmutableIntArray} 649 * instead, which has an {@link ImmutableIntArray#asList asList} view. 650 * 651 * @param backingArray the array to back the list 652 * @return a list view of the array 653 */ 654 public static List<Integer> asList(int... backingArray) { 655 if (backingArray.length == 0) { 656 return emptyList(); 657 } 658 return new IntArrayAsList(backingArray); 659 } 660 661 private static final class IntArrayAsList extends AbstractList<Integer> 662 implements RandomAccess, Serializable { 663 final int[] array; 664 final int start; 665 final int end; 666 667 IntArrayAsList(int[] array) { 668 this(array, 0, array.length); 669 } 670 671 IntArrayAsList(int[] array, int start, int end) { 672 this.array = array; 673 this.start = start; 674 this.end = end; 675 } 676 677 @Override 678 public int size() { 679 return end - start; 680 } 681 682 @Override 683 public boolean isEmpty() { 684 return false; 685 } 686 687 @Override 688 public Integer get(int index) { 689 checkElementIndex(index, size()); 690 return array[start + index]; 691 } 692 693 @Override 694 public Spliterator.OfInt spliterator() { 695 return Spliterators.spliterator(array, start, end, 0); 696 } 697 698 @Override 699 public boolean contains(@Nullable Object target) { 700 // Overridden to prevent a ton of boxing 701 return (target instanceof Integer) && Ints.indexOf(array, (Integer) target, start, end) != -1; 702 } 703 704 @Override 705 public int indexOf(@Nullable Object target) { 706 // Overridden to prevent a ton of boxing 707 if (target instanceof Integer) { 708 int i = Ints.indexOf(array, (Integer) target, start, end); 709 if (i >= 0) { 710 return i - start; 711 } 712 } 713 return -1; 714 } 715 716 @Override 717 public int lastIndexOf(@Nullable Object target) { 718 // Overridden to prevent a ton of boxing 719 if (target instanceof Integer) { 720 int i = Ints.lastIndexOf(array, (Integer) target, start, end); 721 if (i >= 0) { 722 return i - start; 723 } 724 } 725 return -1; 726 } 727 728 @Override 729 public Integer set(int index, Integer element) { 730 checkElementIndex(index, size()); 731 int oldValue = array[start + index]; 732 // checkNotNull for GWT (do not optimize) 733 array[start + index] = checkNotNull(element); 734 return oldValue; 735 } 736 737 @Override 738 public List<Integer> subList(int fromIndex, int toIndex) { 739 int size = size(); 740 checkPositionIndexes(fromIndex, toIndex, size); 741 if (fromIndex == toIndex) { 742 return emptyList(); 743 } 744 return new IntArrayAsList(array, start + fromIndex, start + toIndex); 745 } 746 747 @Override 748 public boolean equals(@Nullable Object object) { 749 if (object == this) { 750 return true; 751 } 752 if (object instanceof IntArrayAsList) { 753 IntArrayAsList that = (IntArrayAsList) object; 754 int size = size(); 755 if (that.size() != size) { 756 return false; 757 } 758 for (int i = 0; i < size; i++) { 759 if (array[start + i] != that.array[that.start + i]) { 760 return false; 761 } 762 } 763 return true; 764 } 765 return super.equals(object); 766 } 767 768 @Override 769 public int hashCode() { 770 int result = 1; 771 for (int i = start; i < end; i++) { 772 result = 31 * result + Integer.hashCode(array[i]); 773 } 774 return result; 775 } 776 777 @Override 778 public String toString() { 779 StringBuilder builder = new StringBuilder(size() * 5); 780 builder.append('[').append(array[start]); 781 for (int i = start + 1; i < end; i++) { 782 builder.append(", ").append(array[i]); 783 } 784 return builder.append(']').toString(); 785 } 786 787 int[] toIntArray() { 788 return Arrays.copyOfRange(array, start, end); 789 } 790 791 @GwtIncompatible @J2ktIncompatible private static final long serialVersionUID = 0; 792 } 793 794 /** 795 * Parses the specified string as a signed decimal integer value. The ASCII character {@code '-'} 796 * (U+002D) is recognized as the minus sign. 797 * 798 * <p>Unlike {@link Integer#parseInt(String)}, this method returns {@code null} instead of 799 * throwing an exception if parsing fails. Additionally, this method only accepts ASCII digits, 800 * and returns {@code null} if non-ASCII digits are present in the string. 801 * 802 * <p>Note that strings prefixed with ASCII {@code '+'} are rejected, even though {@link 803 * Integer#parseInt(String)} accepts them. 804 * 805 * @param string the string representation of an integer value 806 * @return the integer value represented by {@code string}, or {@code null} if {@code string} has 807 * a length of zero or cannot be parsed as an integer value 808 * @throws NullPointerException if {@code string} is {@code null} 809 * @since 11.0 810 */ 811 public static @Nullable Integer tryParse(String string) { 812 return tryParse(string, 10); 813 } 814 815 /** 816 * Parses the specified string as a signed integer value using the specified radix. The ASCII 817 * character {@code '-'} (U+002D) is recognized as the minus sign. 818 * 819 * <p>Unlike {@link Integer#parseInt(String, int)}, this method returns {@code null} instead of 820 * throwing an exception if parsing fails. Additionally, this method only accepts ASCII digits, 821 * and returns {@code null} if non-ASCII digits are present in the string. 822 * 823 * <p>Note that strings prefixed with ASCII {@code '+'} are rejected, even though {@link 824 * Integer#parseInt(String)} accepts them. 825 * 826 * @param string the string representation of an integer value 827 * @param radix the radix to use when parsing 828 * @return the integer value represented by {@code string} using {@code radix}, or {@code null} if 829 * {@code string} has a length of zero or cannot be parsed as an integer value 830 * @throws IllegalArgumentException if {@code radix < Character.MIN_RADIX} or {@code radix > 831 * Character.MAX_RADIX} 832 * @throws NullPointerException if {@code string} is {@code null} 833 * @since 19.0 834 */ 835 public static @Nullable Integer tryParse(String string, int radix) { 836 Long result = Longs.tryParse(string, radix); 837 if (result == null || result != result.intValue()) { 838 return null; 839 } else { 840 return result.intValue(); 841 } 842 } 843}