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