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