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