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