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 * @param value the {@code int} value to constrain 268 * @param min the lower bound (inclusive) of the range to constrain {@code value} to 269 * @param max the upper bound (inclusive) of the range to constrain {@code value} to 270 * @throws IllegalArgumentException if {@code min > max} 271 * @since 21.0 272 */ 273 public static int constrainToRange(int value, int min, int max) { 274 checkArgument(min <= max, "min (%s) must be less than or equal to max (%s)", min, max); 275 return Math.min(Math.max(value, min), max); 276 } 277 278 /** 279 * Returns the values from each provided array combined into a single array. For example, {@code 280 * concat(new int[] {a, b}, new int[] {}, new int[] {c}} returns the array {@code {a, b, c}}. 281 * 282 * @param arrays zero or more {@code int} arrays 283 * @return a single array containing all the values from the source arrays, in order 284 */ 285 public static int[] concat(int[]... arrays) { 286 int length = 0; 287 for (int[] array : arrays) { 288 length += array.length; 289 } 290 int[] result = new int[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 /** 300 * Returns a big-endian representation of {@code value} in a 4-element byte array; equivalent to 301 * {@code ByteBuffer.allocate(4).putInt(value).array()}. For example, the input value {@code 302 * 0x12131415} would yield the byte array {@code {0x12, 0x13, 0x14, 0x15}}. 303 * 304 * <p>If you need to convert and concatenate several values (possibly even of different types), 305 * use a shared {@link java.nio.ByteBuffer} instance, or use {@link 306 * com.google.common.io.ByteStreams#newDataOutput()} to get a growable buffer. 307 */ 308 public static byte[] toByteArray(int value) { 309 return new byte[] { 310 (byte) (value >> 24), (byte) (value >> 16), (byte) (value >> 8), (byte) value 311 }; 312 } 313 314 /** 315 * Returns the {@code int} value whose big-endian representation is stored in the first 4 bytes of 316 * {@code bytes}; equivalent to {@code ByteBuffer.wrap(bytes).getInt()}. For example, the input 317 * byte array {@code {0x12, 0x13, 0x14, 0x15, 0x33}} would yield the {@code int} value {@code 318 * 0x12131415}. 319 * 320 * <p>Arguably, it's preferable to use {@link java.nio.ByteBuffer}; that library exposes much more 321 * flexibility at little cost in readability. 322 * 323 * @throws IllegalArgumentException if {@code bytes} has fewer than 4 elements 324 */ 325 public static int fromByteArray(byte[] bytes) { 326 checkArgument(bytes.length >= BYTES, "array too small: %s < %s", bytes.length, BYTES); 327 return fromBytes(bytes[0], bytes[1], bytes[2], bytes[3]); 328 } 329 330 /** 331 * Returns the {@code int} value whose byte representation is the given 4 bytes, in big-endian 332 * order; equivalent to {@code Ints.fromByteArray(new byte[] {b1, b2, b3, b4})}. 333 * 334 * @since 7.0 335 */ 336 public static int fromBytes(byte b1, byte b2, byte b3, byte b4) { 337 return b1 << 24 | (b2 & 0xFF) << 16 | (b3 & 0xFF) << 8 | (b4 & 0xFF); 338 } 339 340 private static final class IntConverter extends Converter<String, Integer> 341 implements Serializable { 342 static final Converter<String, Integer> INSTANCE = new IntConverter(); 343 344 @Override 345 protected Integer doForward(String value) { 346 return Integer.decode(value); 347 } 348 349 @Override 350 protected String doBackward(Integer value) { 351 return value.toString(); 352 } 353 354 @Override 355 public String toString() { 356 return "Ints.stringConverter()"; 357 } 358 359 private Object readResolve() { 360 return INSTANCE; 361 } 362 363 private static final long serialVersionUID = 1; 364 } 365 366 /** 367 * Returns a serializable converter object that converts between strings and integers using {@link 368 * Integer#decode} and {@link Integer#toString()}. The returned converter throws {@link 369 * NumberFormatException} if the input string is invalid. 370 * 371 * <p><b>Warning:</b> please see {@link Integer#decode} to understand exactly how strings are 372 * parsed. For example, the string {@code "0123"} is treated as <i>octal</i> and converted to the 373 * value {@code 83}. 374 * 375 * @since 16.0 376 */ 377 public static Converter<String, Integer> stringConverter() { 378 return IntConverter.INSTANCE; 379 } 380 381 /** 382 * Returns an array containing the same values as {@code array}, but guaranteed to be of a 383 * specified minimum length. If {@code array} already has a length of at least {@code minLength}, 384 * it is returned directly. Otherwise, a new array of size {@code minLength + padding} is 385 * returned, containing the values of {@code array}, and zeroes in the remaining places. 386 * 387 * @param array the source array 388 * @param minLength the minimum length the returned array must guarantee 389 * @param padding an extra amount to "grow" the array by if growth is necessary 390 * @throws IllegalArgumentException if {@code minLength} or {@code padding} is negative 391 * @return an array containing the values of {@code array}, with guaranteed minimum length {@code 392 * minLength} 393 */ 394 public static int[] ensureCapacity(int[] array, int minLength, int padding) { 395 checkArgument(minLength >= 0, "Invalid minLength: %s", minLength); 396 checkArgument(padding >= 0, "Invalid padding: %s", padding); 397 return (array.length < minLength) ? Arrays.copyOf(array, minLength + padding) : array; 398 } 399 400 /** 401 * Returns a string containing the supplied {@code int} values separated by {@code separator}. For 402 * example, {@code join("-", 1, 2, 3)} returns the string {@code "1-2-3"}. 403 * 404 * @param separator the text that should appear between consecutive values in the resulting string 405 * (but not at the start or end) 406 * @param array an array of {@code int} values, possibly empty 407 */ 408 public static String join(String separator, int... array) { 409 checkNotNull(separator); 410 if (array.length == 0) { 411 return ""; 412 } 413 414 // For pre-sizing a builder, just get the right order of magnitude 415 StringBuilder builder = new StringBuilder(array.length * 5); 416 builder.append(array[0]); 417 for (int i = 1; i < array.length; i++) { 418 builder.append(separator).append(array[i]); 419 } 420 return builder.toString(); 421 } 422 423 /** 424 * Returns a comparator that compares two {@code int} arrays <a 425 * href="http://en.wikipedia.org/wiki/Lexicographical_order">lexicographically</a>. That is, it 426 * compares, using {@link #compare(int, int)}), the first pair of values that follow any common 427 * prefix, or when one array is a prefix of the other, treats the shorter array as the lesser. For 428 * example, {@code [] < [1] < [1, 2] < [2]}. 429 * 430 * <p>The returned comparator is inconsistent with {@link Object#equals(Object)} (since arrays 431 * support only identity equality), but it is consistent with {@link Arrays#equals(int[], int[])}. 432 * 433 * @since 2.0 434 */ 435 public static Comparator<int[]> lexicographicalComparator() { 436 return LexicographicalComparator.INSTANCE; 437 } 438 439 private enum LexicographicalComparator implements Comparator<int[]> { 440 INSTANCE; 441 442 @Override 443 public int compare(int[] left, int[] right) { 444 int minLength = Math.min(left.length, right.length); 445 for (int i = 0; i < minLength; i++) { 446 int result = Integer.compare(left[i], right[i]); 447 if (result != 0) { 448 return result; 449 } 450 } 451 return left.length - right.length; 452 } 453 454 @Override 455 public String toString() { 456 return "Ints.lexicographicalComparator()"; 457 } 458 } 459 460 /** 461 * Sorts the elements of {@code array} in descending order. 462 * 463 * @since 23.1 464 */ 465 public static void sortDescending(int[] array) { 466 checkNotNull(array); 467 sortDescending(array, 0, array.length); 468 } 469 470 /** 471 * Sorts the elements of {@code array} between {@code fromIndex} inclusive and {@code toIndex} 472 * exclusive in descending order. 473 * 474 * @since 23.1 475 */ 476 public static void sortDescending(int[] array, int fromIndex, int toIndex) { 477 checkNotNull(array); 478 checkPositionIndexes(fromIndex, toIndex, array.length); 479 Arrays.sort(array, fromIndex, toIndex); 480 reverse(array, fromIndex, toIndex); 481 } 482 483 /** 484 * Reverses the elements of {@code array}. This is equivalent to {@code 485 * Collections.reverse(Ints.asList(array))}, but is likely to be more efficient. 486 * 487 * @since 23.1 488 */ 489 public static void reverse(int[] array) { 490 checkNotNull(array); 491 reverse(array, 0, array.length); 492 } 493 494 /** 495 * Reverses the elements of {@code array} between {@code fromIndex} inclusive and {@code toIndex} 496 * exclusive. This is equivalent to {@code 497 * Collections.reverse(Ints.asList(array).subList(fromIndex, toIndex))}, but is likely to be more 498 * efficient. 499 * 500 * @throws IndexOutOfBoundsException if {@code fromIndex < 0}, {@code toIndex > array.length}, or 501 * {@code toIndex > fromIndex} 502 * @since 23.1 503 */ 504 public static void reverse(int[] array, int fromIndex, int toIndex) { 505 checkNotNull(array); 506 checkPositionIndexes(fromIndex, toIndex, array.length); 507 for (int i = fromIndex, j = toIndex - 1; i < j; i++, j--) { 508 int tmp = array[i]; 509 array[i] = array[j]; 510 array[j] = tmp; 511 } 512 } 513 514 /** 515 * Performs a right rotation of {@code array} of "distance" places, so that the first element is 516 * moved to index "distance", and the element at index {@code i} ends up at index {@code (distance 517 * + i) mod array.length}. This is equivalent to {@code Collections.rotate(Ints.asList(array), 518 * distance)}, but is considerably faster and avoids allocation and garbage collection. 519 * 520 * <p>The provided "distance" may be negative, which will rotate left. 521 * 522 * @since 32.0.0 523 */ 524 public static void rotate(int[] array, int distance) { 525 rotate(array, distance, 0, array.length); 526 } 527 528 /** 529 * Performs a right rotation of {@code array} between {@code fromIndex} inclusive and {@code 530 * toIndex} exclusive. This is equivalent to {@code 531 * Collections.rotate(Ints.asList(array).subList(fromIndex, toIndex), distance)}, but is 532 * considerably faster and avoids allocations and garbage collection. 533 * 534 * <p>The provided "distance" may be negative, which will rotate left. 535 * 536 * @throws IndexOutOfBoundsException if {@code fromIndex < 0}, {@code toIndex > array.length}, or 537 * {@code toIndex > fromIndex} 538 * @since 32.0.0 539 */ 540 public static void rotate(int[] array, int distance, int fromIndex, int toIndex) { 541 // There are several well-known algorithms for rotating part of an array (or, equivalently, 542 // exchanging two blocks of memory). This classic text by Gries and Mills mentions several: 543 // https://ecommons.cornell.edu/bitstream/handle/1813/6292/81-452.pdf. 544 // (1) "Reversal", the one we have here. 545 // (2) "Dolphin". If we're rotating an array a of size n by a distance of d, then element a[0] 546 // ends up at a[d], which in turn ends up at a[2d], and so on until we get back to a[0]. 547 // (All indices taken mod n.) If d and n are mutually prime, all elements will have been 548 // moved at that point. Otherwise, we can rotate the cycle a[1], a[1 + d], a[1 + 2d], etc, 549 // then a[2] etc, and so on until we have rotated all elements. There are gcd(d, n) cycles 550 // in all. 551 // (3) "Successive". We can consider that we are exchanging a block of size d (a[0..d-1]) with a 552 // block of size n-d (a[d..n-1]), where in general these blocks have different sizes. If we 553 // imagine a line separating the first block from the second, we can proceed by exchanging 554 // the smaller of these blocks with the far end of the other one. That leaves us with a 555 // smaller version of the same problem. 556 // Say we are rotating abcdefgh by 5. We start with abcde|fgh. The smaller block is [fgh]: 557 // [abc]de|[fgh] -> [fgh]de|[abc]. Now [fgh] is in the right place, but we need to swap [de] 558 // with [abc]: fgh[de]|a[bc] -> fgh[bc]|a[de]. Now we need to swap [a] with [bc]: 559 // fgh[b]c|[a]de -> fgh[a]c|[b]de. Finally we need to swap [c] with [b]: 560 // fgha[c]|[b]de -> fgha[b]|[c]de. Because these two blocks are the same size, we are done. 561 // The Dolphin algorithm is attractive because it does the fewest array reads and writes: each 562 // array slot is read and written exactly once. However, it can have very poor memory locality: 563 // benchmarking shows it can take 7 times longer than the other two in some cases. The other two 564 // do n swaps, minus a delta (0 or 2 for Reversal, gcd(d, n) for Successive), so that's about 565 // twice as many reads and writes. But benchmarking shows that they usually perform better than 566 // Dolphin. Reversal is about as good as Successive on average, and it is much simpler, 567 // especially since we already have a `reverse` method. 568 checkNotNull(array); 569 checkPositionIndexes(fromIndex, toIndex, array.length); 570 if (array.length <= 1) { 571 return; 572 } 573 574 int length = toIndex - fromIndex; 575 // Obtain m = (-distance mod length), a non-negative value less than "length". This is how many 576 // places left to rotate. 577 int m = -distance % length; 578 m = (m < 0) ? m + length : m; 579 // The current index of what will become the first element of the rotated section. 580 int newFirstIndex = m + fromIndex; 581 if (newFirstIndex == fromIndex) { 582 return; 583 } 584 585 reverse(array, fromIndex, newFirstIndex); 586 reverse(array, newFirstIndex, toIndex); 587 reverse(array, fromIndex, toIndex); 588 } 589 590 /** 591 * Returns an array containing each value of {@code collection}, converted to a {@code int} value 592 * in the manner of {@link Number#intValue}. 593 * 594 * <p>Elements are copied from the argument collection as if by {@code collection.toArray()}. 595 * Calling this method is as thread-safe as calling that method. 596 * 597 * @param collection a collection of {@code Number} instances 598 * @return an array containing the same values as {@code collection}, in the same order, converted 599 * to primitives 600 * @throws NullPointerException if {@code collection} or any of its elements is null 601 * @since 1.0 (parameter was {@code Collection<Integer>} before 12.0) 602 */ 603 public static int[] toArray(Collection<? extends Number> collection) { 604 if (collection instanceof IntArrayAsList) { 605 return ((IntArrayAsList) collection).toIntArray(); 606 } 607 608 Object[] boxedArray = collection.toArray(); 609 int len = boxedArray.length; 610 int[] array = new int[len]; 611 for (int i = 0; i < len; i++) { 612 // checkNotNull for GWT (do not optimize) 613 array[i] = ((Number) checkNotNull(boxedArray[i])).intValue(); 614 } 615 return array; 616 } 617 618 /** 619 * Returns a fixed-size list backed by the specified array, similar to {@link 620 * Arrays#asList(Object[])}. The list supports {@link List#set(int, Object)}, but any attempt to 621 * set a value to {@code null} will result in a {@link NullPointerException}. 622 * 623 * <p>The returned list maintains the values, but not the identities, of {@code Integer} objects 624 * written to or read from it. For example, whether {@code list.get(0) == list.get(0)} is true for 625 * the returned list is unspecified. 626 * 627 * <p>The returned list is serializable. 628 * 629 * <p><b>Note:</b> when possible, you should represent your data as an {@link ImmutableIntArray} 630 * instead, which has an {@link ImmutableIntArray#asList asList} view. 631 * 632 * @param backingArray the array to back the list 633 * @return a list view of the array 634 */ 635 public static List<Integer> asList(int... backingArray) { 636 if (backingArray.length == 0) { 637 return Collections.emptyList(); 638 } 639 return new IntArrayAsList(backingArray); 640 } 641 642 @GwtCompatible 643 private static class IntArrayAsList extends AbstractList<Integer> 644 implements RandomAccess, Serializable { 645 final int[] array; 646 final int start; 647 final int end; 648 649 IntArrayAsList(int[] array) { 650 this(array, 0, array.length); 651 } 652 653 IntArrayAsList(int[] array, int start, int end) { 654 this.array = array; 655 this.start = start; 656 this.end = end; 657 } 658 659 @Override 660 public int size() { 661 return end - start; 662 } 663 664 @Override 665 public boolean isEmpty() { 666 return false; 667 } 668 669 @Override 670 public Integer get(int index) { 671 checkElementIndex(index, size()); 672 return array[start + index]; 673 } 674 675 @Override 676 public Spliterator.OfInt spliterator() { 677 return Spliterators.spliterator(array, start, end, 0); 678 } 679 680 @Override 681 public boolean contains(@CheckForNull Object target) { 682 // Overridden to prevent a ton of boxing 683 return (target instanceof Integer) && Ints.indexOf(array, (Integer) target, start, end) != -1; 684 } 685 686 @Override 687 public int indexOf(@CheckForNull Object target) { 688 // Overridden to prevent a ton of boxing 689 if (target instanceof Integer) { 690 int i = Ints.indexOf(array, (Integer) target, start, end); 691 if (i >= 0) { 692 return i - start; 693 } 694 } 695 return -1; 696 } 697 698 @Override 699 public int lastIndexOf(@CheckForNull Object target) { 700 // Overridden to prevent a ton of boxing 701 if (target instanceof Integer) { 702 int i = Ints.lastIndexOf(array, (Integer) target, start, end); 703 if (i >= 0) { 704 return i - start; 705 } 706 } 707 return -1; 708 } 709 710 @Override 711 public Integer set(int index, Integer element) { 712 checkElementIndex(index, size()); 713 int oldValue = array[start + index]; 714 // checkNotNull for GWT (do not optimize) 715 array[start + index] = checkNotNull(element); 716 return oldValue; 717 } 718 719 @Override 720 public List<Integer> subList(int fromIndex, int toIndex) { 721 int size = size(); 722 checkPositionIndexes(fromIndex, toIndex, size); 723 if (fromIndex == toIndex) { 724 return Collections.emptyList(); 725 } 726 return new IntArrayAsList(array, start + fromIndex, start + toIndex); 727 } 728 729 @Override 730 public boolean equals(@CheckForNull Object object) { 731 if (object == this) { 732 return true; 733 } 734 if (object instanceof IntArrayAsList) { 735 IntArrayAsList that = (IntArrayAsList) object; 736 int size = size(); 737 if (that.size() != size) { 738 return false; 739 } 740 for (int i = 0; i < size; i++) { 741 if (array[start + i] != that.array[that.start + i]) { 742 return false; 743 } 744 } 745 return true; 746 } 747 return super.equals(object); 748 } 749 750 @Override 751 public int hashCode() { 752 int result = 1; 753 for (int i = start; i < end; i++) { 754 result = 31 * result + Ints.hashCode(array[i]); 755 } 756 return result; 757 } 758 759 @Override 760 public String toString() { 761 StringBuilder builder = new StringBuilder(size() * 5); 762 builder.append('[').append(array[start]); 763 for (int i = start + 1; i < end; i++) { 764 builder.append(", ").append(array[i]); 765 } 766 return builder.append(']').toString(); 767 } 768 769 int[] toIntArray() { 770 return Arrays.copyOfRange(array, start, end); 771 } 772 773 private static final long serialVersionUID = 0; 774 } 775 776 /** 777 * Parses the specified string as a signed decimal integer value. The ASCII character {@code '-'} 778 * (<code>'\u002D'</code>) is recognized as the minus sign. 779 * 780 * <p>Unlike {@link Integer#parseInt(String)}, this method returns {@code null} instead of 781 * throwing an exception if parsing fails. Additionally, this method only accepts ASCII digits, 782 * and returns {@code null} if non-ASCII digits are present in the string. 783 * 784 * <p>Note that strings prefixed with ASCII {@code '+'} are rejected, even though {@link 785 * Integer#parseInt(String)} accepts them. 786 * 787 * @param string the string representation of an integer value 788 * @return the integer value represented by {@code string}, or {@code null} if {@code string} has 789 * a length of zero or cannot be parsed as an integer value 790 * @throws NullPointerException if {@code string} is {@code null} 791 * @since 11.0 792 */ 793 @CheckForNull 794 public static Integer tryParse(String string) { 795 return tryParse(string, 10); 796 } 797 798 /** 799 * Parses the specified string as a signed integer value using the specified radix. The ASCII 800 * character {@code '-'} (<code>'\u002D'</code>) is recognized as the minus sign. 801 * 802 * <p>Unlike {@link Integer#parseInt(String, int)}, this method returns {@code null} instead of 803 * throwing an exception if parsing fails. Additionally, this method only accepts ASCII digits, 804 * and returns {@code null} if non-ASCII digits are present in the string. 805 * 806 * <p>Note that strings prefixed with ASCII {@code '+'} are rejected, even though {@link 807 * Integer#parseInt(String)} accepts them. 808 * 809 * @param string the string representation of an integer value 810 * @param radix the radix to use when parsing 811 * @return the integer value represented by {@code string} using {@code radix}, or {@code null} if 812 * {@code string} has a length of zero or cannot be parsed as an integer value 813 * @throws IllegalArgumentException if {@code radix < Character.MIN_RADIX} or {@code radix > 814 * Character.MAX_RADIX} 815 * @throws NullPointerException if {@code string} is {@code null} 816 * @since 19.0 817 */ 818 @CheckForNull 819 public static Integer tryParse(String string, int radix) { 820 Long result = Longs.tryParse(string, radix); 821 if (result == null || result.longValue() != result.intValue()) { 822 return null; 823 } else { 824 return result.intValue(); 825 } 826 } 827}