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.max; 022import static java.lang.Math.min; 023 024import com.google.common.annotations.GwtCompatible; 025import com.google.common.annotations.GwtIncompatible; 026import com.google.common.base.Converter; 027import com.google.errorprone.annotations.InlineMe; 028import java.io.Serializable; 029import java.util.AbstractList; 030import java.util.Arrays; 031import java.util.Collection; 032import java.util.Collections; 033import java.util.Comparator; 034import java.util.List; 035import java.util.RandomAccess; 036import java.util.Spliterator; 037import java.util.Spliterators; 038import javax.annotation.CheckForNull; 039 040/** 041 * Static utility methods pertaining to {@code int} primitives, that are not already found in either 042 * {@link Integer} or {@link Arrays}. 043 * 044 * <p>See the Guava User Guide article on <a 045 * href="https://github.com/google/guava/wiki/PrimitivesExplained">primitive utilities</a>. 046 * 047 * @author Kevin Bourrillion 048 * @since 1.0 049 */ 050@GwtCompatible(emulated = true) 051@ElementTypesAreNonnullByDefault 052public final class Ints extends IntsMethodsForWeb { 053 private Ints() {} 054 055 /** 056 * The number of bytes required to represent a primitive {@code int} value. 057 * 058 * <p><b>Java 8+ users:</b> use {@link Integer#BYTES} instead. 059 */ 060 public static final int BYTES = Integer.SIZE / Byte.SIZE; 061 062 /** 063 * The largest power of two that can be represented as an {@code int}. 064 * 065 * @since 10.0 066 */ 067 public static final int MAX_POWER_OF_TWO = 1 << (Integer.SIZE - 2); 068 069 /** 070 * Returns a hash code for {@code value}; equal to the result of invoking {@code ((Integer) 071 * value).hashCode()}. 072 * 073 * <p><b>Java 8+ users:</b> use {@link Integer#hashCode(int)} instead. 074 * 075 * @param value a primitive {@code int} value 076 * @return a hash code for the value 077 */ 078 public static int hashCode(int value) { 079 return value; 080 } 081 082 /** 083 * Returns the {@code int} value that is equal to {@code value}, if possible. 084 * 085 * @param value any value in the range of the {@code int} type 086 * @return the {@code int} value that equals {@code value} 087 * @throws IllegalArgumentException if {@code value} is greater than {@link Integer#MAX_VALUE} or 088 * less than {@link Integer#MIN_VALUE} 089 */ 090 public static int checkedCast(long value) { 091 int result = (int) value; 092 checkArgument(result == value, "Out of range: %s", value); 093 return result; 094 } 095 096 /** 097 * Returns the {@code int} nearest in value to {@code value}. 098 * 099 * @param value any {@code long} value 100 * @return the same value cast to {@code int} if it is in the range of the {@code int} type, 101 * {@link Integer#MAX_VALUE} if it is too large, or {@link Integer#MIN_VALUE} if it is too 102 * small 103 */ 104 public static int saturatedCast(long value) { 105 if (value > Integer.MAX_VALUE) { 106 return Integer.MAX_VALUE; 107 } 108 if (value < Integer.MIN_VALUE) { 109 return Integer.MIN_VALUE; 110 } 111 return (int) value; 112 } 113 114 /** 115 * Compares the two specified {@code int} values. The sign of the value returned is the same as 116 * that of {@code ((Integer) a).compareTo(b)}. 117 * 118 * <p><b>Note:</b> this method is now unnecessary and should be treated as deprecated; use the 119 * equivalent {@link Integer#compare} method instead. 120 * 121 * @param a the first {@code int} to compare 122 * @param b the second {@code int} to compare 123 * @return a negative value if {@code a} is less than {@code b}; a positive value if {@code a} is 124 * greater than {@code b}; or zero if they are equal 125 */ 126 @InlineMe(replacement = "Integer.compare(a, b)") 127 public static int compare(int a, int b) { 128 return Integer.compare(a, b); 129 } 130 131 /** 132 * Returns {@code true} if {@code target} is present as an element anywhere in {@code array}. 133 * 134 * @param array an array of {@code int} values, possibly empty 135 * @param target a primitive {@code int} value 136 * @return {@code true} if {@code array[i] == target} for some value of {@code i} 137 */ 138 public static boolean contains(int[] array, int target) { 139 for (int value : array) { 140 if (value == target) { 141 return true; 142 } 143 } 144 return false; 145 } 146 147 /** 148 * Returns the index of the first appearance of the value {@code target} in {@code array}. 149 * 150 * @param array an array of {@code int} values, possibly empty 151 * @param target a primitive {@code int} value 152 * @return the least index {@code i} for which {@code array[i] == target}, or {@code -1} if no 153 * such index exists. 154 */ 155 public static int indexOf(int[] array, int target) { 156 return indexOf(array, target, 0, array.length); 157 } 158 159 // TODO(kevinb): consider making this public 160 private static int indexOf(int[] array, int target, int start, int end) { 161 for (int i = start; i < end; i++) { 162 if (array[i] == target) { 163 return i; 164 } 165 } 166 return -1; 167 } 168 169 /** 170 * Returns the start position of the first occurrence of the specified {@code target} within 171 * {@code array}, or {@code -1} if there is no such occurrence. 172 * 173 * <p>More formally, returns the lowest index {@code i} such that {@code Arrays.copyOfRange(array, 174 * i, i + target.length)} contains exactly the same elements as {@code target}. 175 * 176 * @param array the array to search for the sequence {@code target} 177 * @param target the array to search for as a sub-sequence of {@code array} 178 */ 179 public static int indexOf(int[] array, int[] target) { 180 checkNotNull(array, "array"); 181 checkNotNull(target, "target"); 182 if (target.length == 0) { 183 return 0; 184 } 185 186 outer: 187 for (int i = 0; i < array.length - target.length + 1; i++) { 188 for (int j = 0; j < target.length; j++) { 189 if (array[i + j] != target[j]) { 190 continue outer; 191 } 192 } 193 return i; 194 } 195 return -1; 196 } 197 198 /** 199 * Returns the index of the last appearance of the value {@code target} in {@code array}. 200 * 201 * @param array an array of {@code int} values, possibly empty 202 * @param target a primitive {@code int} value 203 * @return the greatest index {@code i} for which {@code array[i] == target}, or {@code -1} if no 204 * such index exists. 205 */ 206 public static int lastIndexOf(int[] array, int target) { 207 return lastIndexOf(array, target, 0, array.length); 208 } 209 210 // TODO(kevinb): consider making this public 211 private static int lastIndexOf(int[] array, int target, int start, int end) { 212 for (int i = end - 1; i >= start; i--) { 213 if (array[i] == target) { 214 return i; 215 } 216 } 217 return -1; 218 } 219 220 /** 221 * Returns the least value present in {@code array}. 222 * 223 * @param array a <i>nonempty</i> array of {@code int} values 224 * @return the value present in {@code array} that is less than or equal to every other value in 225 * the array 226 * @throws IllegalArgumentException if {@code array} is empty 227 */ 228 @GwtIncompatible( 229 "Available in GWT! Annotation is to avoid conflict with GWT specialization of base class.") 230 public static int min(int... array) { 231 checkArgument(array.length > 0); 232 int min = array[0]; 233 for (int i = 1; i < array.length; i++) { 234 if (array[i] < min) { 235 min = array[i]; 236 } 237 } 238 return min; 239 } 240 241 /** 242 * Returns the greatest value present in {@code array}. 243 * 244 * @param array a <i>nonempty</i> array of {@code int} values 245 * @return the value present in {@code array} that is greater than or equal to every other value 246 * in the array 247 * @throws IllegalArgumentException if {@code array} is empty 248 */ 249 @GwtIncompatible( 250 "Available in GWT! Annotation is to avoid conflict with GWT specialization of base class.") 251 public static int max(int... array) { 252 checkArgument(array.length > 0); 253 int max = array[0]; 254 for (int i = 1; i < array.length; i++) { 255 if (array[i] > max) { 256 max = array[i]; 257 } 258 } 259 return max; 260 } 261 262 /** 263 * Returns the value nearest to {@code value} which is within the closed range {@code [min..max]}. 264 * 265 * <p>If {@code value} is within the range {@code [min..max]}, {@code value} is returned 266 * unchanged. If {@code value} is less than {@code min}, {@code min} is returned, and if {@code 267 * value} is greater than {@code max}, {@code max} is returned. 268 * 269 * <p><b>Java 21+ users:</b> Use {@code Math.clamp} instead. Note that that method is capable of 270 * constraining a {@code long} input to an {@code int} range. 271 * 272 * @param value the {@code int} value to constrain 273 * @param min the lower bound (inclusive) of the range to constrain {@code value} to 274 * @param max the upper bound (inclusive) of the range to constrain {@code value} to 275 * @throws IllegalArgumentException if {@code min > max} 276 * @since 21.0 277 */ 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 min(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 public int compare(int[] left, int[] right) { 459 int minLength = min(left.length, right.length); 460 for (int i = 0; i < minLength; i++) { 461 int result = Integer.compare(left[i], right[i]); 462 if (result != 0) { 463 return result; 464 } 465 } 466 return left.length - right.length; 467 } 468 469 @Override 470 public String toString() { 471 return "Ints.lexicographicalComparator()"; 472 } 473 } 474 475 /** 476 * Sorts the elements of {@code array} in descending order. 477 * 478 * @since 23.1 479 */ 480 public static void sortDescending(int[] array) { 481 checkNotNull(array); 482 sortDescending(array, 0, array.length); 483 } 484 485 /** 486 * Sorts the elements of {@code array} between {@code fromIndex} inclusive and {@code toIndex} 487 * exclusive in descending order. 488 * 489 * @since 23.1 490 */ 491 public static void sortDescending(int[] array, int fromIndex, int toIndex) { 492 checkNotNull(array); 493 checkPositionIndexes(fromIndex, toIndex, array.length); 494 Arrays.sort(array, fromIndex, toIndex); 495 reverse(array, fromIndex, toIndex); 496 } 497 498 /** 499 * Reverses the elements of {@code array}. This is equivalent to {@code 500 * Collections.reverse(Ints.asList(array))}, but is likely to be more efficient. 501 * 502 * @since 23.1 503 */ 504 public static void reverse(int[] array) { 505 checkNotNull(array); 506 reverse(array, 0, array.length); 507 } 508 509 /** 510 * Reverses the elements of {@code array} between {@code fromIndex} inclusive and {@code toIndex} 511 * exclusive. This is equivalent to {@code 512 * Collections.reverse(Ints.asList(array).subList(fromIndex, toIndex))}, but is likely to be more 513 * efficient. 514 * 515 * @throws IndexOutOfBoundsException if {@code fromIndex < 0}, {@code toIndex > array.length}, or 516 * {@code toIndex > fromIndex} 517 * @since 23.1 518 */ 519 public static void reverse(int[] array, int fromIndex, int toIndex) { 520 checkNotNull(array); 521 checkPositionIndexes(fromIndex, toIndex, array.length); 522 for (int i = fromIndex, j = toIndex - 1; i < j; i++, j--) { 523 int tmp = array[i]; 524 array[i] = array[j]; 525 array[j] = tmp; 526 } 527 } 528 529 /** 530 * Performs a right rotation of {@code array} of "distance" places, so that the first element is 531 * moved to index "distance", and the element at index {@code i} ends up at index {@code (distance 532 * + i) mod array.length}. This is equivalent to {@code Collections.rotate(Ints.asList(array), 533 * distance)}, but is considerably faster and avoids allocation and garbage collection. 534 * 535 * <p>The provided "distance" may be negative, which will rotate left. 536 * 537 * @since 32.0.0 538 */ 539 public static void rotate(int[] array, int distance) { 540 rotate(array, distance, 0, array.length); 541 } 542 543 /** 544 * Performs a right rotation of {@code array} between {@code fromIndex} inclusive and {@code 545 * toIndex} exclusive. This is equivalent to {@code 546 * Collections.rotate(Ints.asList(array).subList(fromIndex, toIndex), distance)}, but is 547 * considerably faster and avoids allocations and garbage collection. 548 * 549 * <p>The provided "distance" may be negative, which will rotate left. 550 * 551 * @throws IndexOutOfBoundsException if {@code fromIndex < 0}, {@code toIndex > array.length}, or 552 * {@code toIndex > fromIndex} 553 * @since 32.0.0 554 */ 555 public static void rotate(int[] array, int distance, int fromIndex, int toIndex) { 556 // There are several well-known algorithms for rotating part of an array (or, equivalently, 557 // exchanging two blocks of memory). This classic text by Gries and Mills mentions several: 558 // https://ecommons.cornell.edu/bitstream/handle/1813/6292/81-452.pdf. 559 // (1) "Reversal", the one we have here. 560 // (2) "Dolphin". If we're rotating an array a of size n by a distance of d, then element a[0] 561 // ends up at a[d], which in turn ends up at a[2d], and so on until we get back to a[0]. 562 // (All indices taken mod n.) If d and n are mutually prime, all elements will have been 563 // moved at that point. Otherwise, we can rotate the cycle a[1], a[1 + d], a[1 + 2d], etc, 564 // then a[2] etc, and so on until we have rotated all elements. There are gcd(d, n) cycles 565 // in all. 566 // (3) "Successive". We can consider that we are exchanging a block of size d (a[0..d-1]) with a 567 // block of size n-d (a[d..n-1]), where in general these blocks have different sizes. If we 568 // imagine a line separating the first block from the second, we can proceed by exchanging 569 // the smaller of these blocks with the far end of the other one. That leaves us with a 570 // smaller version of the same problem. 571 // Say we are rotating abcdefgh by 5. We start with abcde|fgh. The smaller block is [fgh]: 572 // [abc]de|[fgh] -> [fgh]de|[abc]. Now [fgh] is in the right place, but we need to swap [de] 573 // with [abc]: fgh[de]|a[bc] -> fgh[bc]|a[de]. Now we need to swap [a] with [bc]: 574 // fgh[b]c|[a]de -> fgh[a]c|[b]de. Finally we need to swap [c] with [b]: 575 // fgha[c]|[b]de -> fgha[b]|[c]de. Because these two blocks are the same size, we are done. 576 // The Dolphin algorithm is attractive because it does the fewest array reads and writes: each 577 // array slot is read and written exactly once. However, it can have very poor memory locality: 578 // benchmarking shows it can take 7 times longer than the other two in some cases. The other two 579 // do n swaps, minus a delta (0 or 2 for Reversal, gcd(d, n) for Successive), so that's about 580 // twice as many reads and writes. But benchmarking shows that they usually perform better than 581 // Dolphin. Reversal is about as good as Successive on average, and it is much simpler, 582 // especially since we already have a `reverse` method. 583 checkNotNull(array); 584 checkPositionIndexes(fromIndex, toIndex, array.length); 585 if (array.length <= 1) { 586 return; 587 } 588 589 int length = toIndex - fromIndex; 590 // Obtain m = (-distance mod length), a non-negative value less than "length". This is how many 591 // places left to rotate. 592 int m = -distance % length; 593 m = (m < 0) ? m + length : m; 594 // The current index of what will become the first element of the rotated section. 595 int newFirstIndex = m + fromIndex; 596 if (newFirstIndex == fromIndex) { 597 return; 598 } 599 600 reverse(array, fromIndex, newFirstIndex); 601 reverse(array, newFirstIndex, toIndex); 602 reverse(array, fromIndex, toIndex); 603 } 604 605 /** 606 * Returns an array containing each value of {@code collection}, converted to a {@code int} value 607 * in the manner of {@link Number#intValue}. 608 * 609 * <p>Elements are copied from the argument collection as if by {@code collection.toArray()}. 610 * Calling this method is as thread-safe as calling that method. 611 * 612 * @param collection a collection of {@code Number} instances 613 * @return an array containing the same values as {@code collection}, in the same order, converted 614 * to primitives 615 * @throws NullPointerException if {@code collection} or any of its elements is null 616 * @since 1.0 (parameter was {@code Collection<Integer>} before 12.0) 617 */ 618 public static int[] toArray(Collection<? extends Number> collection) { 619 if (collection instanceof IntArrayAsList) { 620 return ((IntArrayAsList) collection).toIntArray(); 621 } 622 623 Object[] boxedArray = collection.toArray(); 624 int len = boxedArray.length; 625 int[] array = new int[len]; 626 for (int i = 0; i < len; i++) { 627 // checkNotNull for GWT (do not optimize) 628 array[i] = ((Number) checkNotNull(boxedArray[i])).intValue(); 629 } 630 return array; 631 } 632 633 /** 634 * Returns a fixed-size list backed by the specified array, similar to {@link 635 * Arrays#asList(Object[])}. The list supports {@link List#set(int, Object)}, but any attempt to 636 * set a value to {@code null} will result in a {@link NullPointerException}. 637 * 638 * <p>The returned list maintains the values, but not the identities, of {@code Integer} objects 639 * written to or read from it. For example, whether {@code list.get(0) == list.get(0)} is true for 640 * the returned list is unspecified. 641 * 642 * <p>The returned list is serializable. 643 * 644 * <p><b>Note:</b> when possible, you should represent your data as an {@link ImmutableIntArray} 645 * instead, which has an {@link ImmutableIntArray#asList asList} view. 646 * 647 * @param backingArray the array to back the list 648 * @return a list view of the array 649 */ 650 public static List<Integer> asList(int... backingArray) { 651 if (backingArray.length == 0) { 652 return Collections.emptyList(); 653 } 654 return new IntArrayAsList(backingArray); 655 } 656 657 @GwtCompatible 658 private static class IntArrayAsList extends AbstractList<Integer> 659 implements RandomAccess, Serializable { 660 final int[] array; 661 final int start; 662 final int end; 663 664 IntArrayAsList(int[] array) { 665 this(array, 0, array.length); 666 } 667 668 IntArrayAsList(int[] array, int start, int end) { 669 this.array = array; 670 this.start = start; 671 this.end = end; 672 } 673 674 @Override 675 public int size() { 676 return end - start; 677 } 678 679 @Override 680 public boolean isEmpty() { 681 return false; 682 } 683 684 @Override 685 public Integer get(int index) { 686 checkElementIndex(index, size()); 687 return array[start + index]; 688 } 689 690 @Override 691 public Spliterator.OfInt spliterator() { 692 return Spliterators.spliterator(array, start, end, 0); 693 } 694 695 @Override 696 public boolean contains(@CheckForNull Object target) { 697 // Overridden to prevent a ton of boxing 698 return (target instanceof Integer) && Ints.indexOf(array, (Integer) target, start, end) != -1; 699 } 700 701 @Override 702 public int indexOf(@CheckForNull Object target) { 703 // Overridden to prevent a ton of boxing 704 if (target instanceof Integer) { 705 int i = Ints.indexOf(array, (Integer) target, start, end); 706 if (i >= 0) { 707 return i - start; 708 } 709 } 710 return -1; 711 } 712 713 @Override 714 public int lastIndexOf(@CheckForNull Object target) { 715 // Overridden to prevent a ton of boxing 716 if (target instanceof Integer) { 717 int i = Ints.lastIndexOf(array, (Integer) target, start, end); 718 if (i >= 0) { 719 return i - start; 720 } 721 } 722 return -1; 723 } 724 725 @Override 726 public Integer set(int index, Integer element) { 727 checkElementIndex(index, size()); 728 int oldValue = array[start + index]; 729 // checkNotNull for GWT (do not optimize) 730 array[start + index] = checkNotNull(element); 731 return oldValue; 732 } 733 734 @Override 735 public List<Integer> subList(int fromIndex, int toIndex) { 736 int size = size(); 737 checkPositionIndexes(fromIndex, toIndex, size); 738 if (fromIndex == toIndex) { 739 return Collections.emptyList(); 740 } 741 return new IntArrayAsList(array, start + fromIndex, start + toIndex); 742 } 743 744 @Override 745 public boolean equals(@CheckForNull Object object) { 746 if (object == this) { 747 return true; 748 } 749 if (object instanceof IntArrayAsList) { 750 IntArrayAsList that = (IntArrayAsList) object; 751 int size = size(); 752 if (that.size() != size) { 753 return false; 754 } 755 for (int i = 0; i < size; i++) { 756 if (array[start + i] != that.array[that.start + i]) { 757 return false; 758 } 759 } 760 return true; 761 } 762 return super.equals(object); 763 } 764 765 @Override 766 public int hashCode() { 767 int result = 1; 768 for (int i = start; i < end; i++) { 769 result = 31 * result + Ints.hashCode(array[i]); 770 } 771 return result; 772 } 773 774 @Override 775 public String toString() { 776 StringBuilder builder = new StringBuilder(size() * 5); 777 builder.append('[').append(array[start]); 778 for (int i = start + 1; i < end; i++) { 779 builder.append(", ").append(array[i]); 780 } 781 return builder.append(']').toString(); 782 } 783 784 int[] toIntArray() { 785 return Arrays.copyOfRange(array, start, end); 786 } 787 788 private static final long serialVersionUID = 0; 789 } 790 791 /** 792 * Parses the specified string as a signed decimal integer value. The ASCII character {@code '-'} 793 * (<code>'\u002D'</code>) is recognized as the minus sign. 794 * 795 * <p>Unlike {@link Integer#parseInt(String)}, this method returns {@code null} instead of 796 * throwing an exception if parsing fails. Additionally, this method only accepts ASCII digits, 797 * and returns {@code null} if non-ASCII digits are present in the string. 798 * 799 * <p>Note that strings prefixed with ASCII {@code '+'} are rejected, even though {@link 800 * Integer#parseInt(String)} accepts them. 801 * 802 * @param string the string representation of an integer value 803 * @return the integer value represented by {@code string}, or {@code null} if {@code string} has 804 * a length of zero or cannot be parsed as an integer value 805 * @throws NullPointerException if {@code string} is {@code null} 806 * @since 11.0 807 */ 808 @CheckForNull 809 public static 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 @CheckForNull 834 public static Integer tryParse(String string, int radix) { 835 Long result = Longs.tryParse(string, radix); 836 if (result == null || result.longValue() != result.intValue()) { 837 return null; 838 } else { 839 return result.intValue(); 840 } 841 } 842}