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.Beta;
023import com.google.common.annotations.GwtCompatible;
024import com.google.common.annotations.GwtIncompatible;
025import com.google.common.base.Converter;
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 for Java 7 and later:</b> this method 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  public static int compare(int a, int b) {
125    return (a < b) ? -1 : ((a > b) ? 1 : 0);
126  }
127
128  /**
129   * Returns {@code true} if {@code target} is present as an element anywhere in {@code array}.
130   *
131   * @param array an array of {@code int} values, possibly empty
132   * @param target a primitive {@code int} value
133   * @return {@code true} if {@code array[i] == target} for some value of {@code i}
134   */
135  public static boolean contains(int[] array, int target) {
136    for (int value : array) {
137      if (value == target) {
138        return true;
139      }
140    }
141    return false;
142  }
143
144  /**
145   * Returns the index of the first appearance of the value {@code target} in {@code array}.
146   *
147   * @param array an array of {@code int} values, possibly empty
148   * @param target a primitive {@code int} value
149   * @return the least index {@code i} for which {@code array[i] == target}, or {@code -1} if no
150   *     such index exists.
151   */
152  public static int indexOf(int[] array, int target) {
153    return indexOf(array, target, 0, array.length);
154  }
155
156  // TODO(kevinb): consider making this public
157  private static int indexOf(int[] array, int target, int start, int end) {
158    for (int i = start; i < end; i++) {
159      if (array[i] == target) {
160        return i;
161      }
162    }
163    return -1;
164  }
165
166  /**
167   * Returns the start position of the first occurrence of the specified {@code target} within
168   * {@code array}, or {@code -1} if there is no such occurrence.
169   *
170   * <p>More formally, returns the lowest index {@code i} such that {@code Arrays.copyOfRange(array,
171   * i, i + target.length)} contains exactly the same elements as {@code target}.
172   *
173   * @param array the array to search for the sequence {@code target}
174   * @param target the array to search for as a sub-sequence of {@code array}
175   */
176  public static int indexOf(int[] array, int[] target) {
177    checkNotNull(array, "array");
178    checkNotNull(target, "target");
179    if (target.length == 0) {
180      return 0;
181    }
182
183    outer:
184    for (int i = 0; i < array.length - target.length + 1; i++) {
185      for (int j = 0; j < target.length; j++) {
186        if (array[i + j] != target[j]) {
187          continue outer;
188        }
189      }
190      return i;
191    }
192    return -1;
193  }
194
195  /**
196   * Returns the index of the last appearance of the value {@code target} in {@code array}.
197   *
198   * @param array an array of {@code int} values, possibly empty
199   * @param target a primitive {@code int} value
200   * @return the greatest index {@code i} for which {@code array[i] == target}, or {@code -1} if no
201   *     such index exists.
202   */
203  public static int lastIndexOf(int[] array, int target) {
204    return lastIndexOf(array, target, 0, array.length);
205  }
206
207  // TODO(kevinb): consider making this public
208  private static int lastIndexOf(int[] array, int target, int start, int end) {
209    for (int i = end - 1; i >= start; i--) {
210      if (array[i] == target) {
211        return i;
212      }
213    }
214    return -1;
215  }
216
217  /**
218   * Returns the least value present in {@code array}.
219   *
220   * @param array a <i>nonempty</i> array of {@code int} values
221   * @return the value present in {@code array} that is less than or equal to every other value in
222   *     the array
223   * @throws IllegalArgumentException if {@code array} is empty
224   */
225  @GwtIncompatible(
226      "Available in GWT! Annotation is to avoid conflict with GWT specialization of base class.")
227  public static int min(int... array) {
228    checkArgument(array.length > 0);
229    int min = array[0];
230    for (int i = 1; i < array.length; i++) {
231      if (array[i] < min) {
232        min = array[i];
233      }
234    }
235    return min;
236  }
237
238  /**
239   * Returns the greatest value present in {@code array}.
240   *
241   * @param array a <i>nonempty</i> array of {@code int} values
242   * @return the value present in {@code array} that is greater than or equal to every other value
243   *     in the array
244   * @throws IllegalArgumentException if {@code array} is empty
245   */
246  @GwtIncompatible(
247      "Available in GWT! Annotation is to avoid conflict with GWT specialization of base class.")
248  public static int max(int... array) {
249    checkArgument(array.length > 0);
250    int max = array[0];
251    for (int i = 1; i < array.length; i++) {
252      if (array[i] > max) {
253        max = array[i];
254      }
255    }
256    return max;
257  }
258
259  /**
260   * Returns the value nearest to {@code value} which is within the closed range {@code [min..max]}.
261   *
262   * <p>If {@code value} is within the range {@code [min..max]}, {@code value} is returned
263   * unchanged. If {@code value} is less than {@code min}, {@code min} is returned, and if {@code
264   * value} is greater than {@code max}, {@code max} is returned.
265   *
266   * @param value the {@code int} value to constrain
267   * @param min the lower bound (inclusive) of the range to constrain {@code value} to
268   * @param max the upper bound (inclusive) of the range to constrain {@code value} to
269   * @throws IllegalArgumentException if {@code min > max}
270   * @since 21.0
271   */
272  @Beta
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 IntConverter 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  @Beta
378  public static Converter<String, Integer> stringConverter() {
379    return IntConverter.INSTANCE;
380  }
381
382  /**
383   * Returns an array containing the same values as {@code array}, but guaranteed to be of a
384   * specified minimum length. If {@code array} already has a length of at least {@code minLength},
385   * it is returned directly. Otherwise, a new array of size {@code minLength + padding} is
386   * returned, containing the values of {@code array}, and zeroes in the remaining places.
387   *
388   * @param array the source array
389   * @param minLength the minimum length the returned array must guarantee
390   * @param padding an extra amount to "grow" the array by if growth is necessary
391   * @throws IllegalArgumentException if {@code minLength} or {@code padding} is negative
392   * @return an array containing the values of {@code array}, with guaranteed minimum length {@code
393   *     minLength}
394   */
395  public static int[] ensureCapacity(int[] array, int minLength, int padding) {
396    checkArgument(minLength >= 0, "Invalid minLength: %s", minLength);
397    checkArgument(padding >= 0, "Invalid padding: %s", padding);
398    return (array.length < minLength) ? Arrays.copyOf(array, minLength + padding) : array;
399  }
400
401  /**
402   * Returns a string containing the supplied {@code int} values separated by {@code separator}. For
403   * example, {@code join("-", 1, 2, 3)} returns the string {@code "1-2-3"}.
404   *
405   * @param separator the text that should appear between consecutive values in the resulting string
406   *     (but not at the start or end)
407   * @param array an array of {@code int} values, possibly empty
408   */
409  public static String join(String separator, int... array) {
410    checkNotNull(separator);
411    if (array.length == 0) {
412      return "";
413    }
414
415    // For pre-sizing a builder, just get the right order of magnitude
416    StringBuilder builder = new StringBuilder(array.length * 5);
417    builder.append(array[0]);
418    for (int i = 1; i < array.length; i++) {
419      builder.append(separator).append(array[i]);
420    }
421    return builder.toString();
422  }
423
424  /**
425   * Returns a comparator that compares two {@code int} arrays <a
426   * href="http://en.wikipedia.org/wiki/Lexicographical_order">lexicographically</a>. That is, it
427   * compares, using {@link #compare(int, int)}), the first pair of values that follow any common
428   * prefix, or when one array is a prefix of the other, treats the shorter array as the lesser. For
429   * example, {@code [] < [1] < [1, 2] < [2]}.
430   *
431   * <p>The returned comparator is inconsistent with {@link Object#equals(Object)} (since arrays
432   * support only identity equality), but it is consistent with {@link Arrays#equals(int[], int[])}.
433   *
434   * @since 2.0
435   */
436  public static Comparator<int[]> lexicographicalComparator() {
437    return LexicographicalComparator.INSTANCE;
438  }
439
440  private enum LexicographicalComparator implements Comparator<int[]> {
441    INSTANCE;
442
443    @Override
444    public int compare(int[] left, int[] right) {
445      int minLength = Math.min(left.length, right.length);
446      for (int i = 0; i < minLength; i++) {
447        int result = Ints.compare(left[i], right[i]);
448        if (result != 0) {
449          return result;
450        }
451      }
452      return left.length - right.length;
453    }
454
455    @Override
456    public String toString() {
457      return "Ints.lexicographicalComparator()";
458    }
459  }
460
461  /**
462   * Sorts the elements of {@code array} in descending order.
463   *
464   * @since 23.1
465   */
466  public static void sortDescending(int[] array) {
467    checkNotNull(array);
468    sortDescending(array, 0, array.length);
469  }
470
471  /**
472   * Sorts the elements of {@code array} between {@code fromIndex} inclusive and {@code toIndex}
473   * exclusive in descending order.
474   *
475   * @since 23.1
476   */
477  public static void sortDescending(int[] array, int fromIndex, int toIndex) {
478    checkNotNull(array);
479    checkPositionIndexes(fromIndex, toIndex, array.length);
480    Arrays.sort(array, fromIndex, toIndex);
481    reverse(array, fromIndex, toIndex);
482  }
483
484  /**
485   * Reverses the elements of {@code array}. This is equivalent to {@code
486   * Collections.reverse(Ints.asList(array))}, but is likely to be more efficient.
487   *
488   * @since 23.1
489   */
490  public static void reverse(int[] array) {
491    checkNotNull(array);
492    reverse(array, 0, array.length);
493  }
494
495  /**
496   * Reverses the elements of {@code array} between {@code fromIndex} inclusive and {@code toIndex}
497   * exclusive. This is equivalent to {@code
498   * Collections.reverse(Ints.asList(array).subList(fromIndex, toIndex))}, but is likely to be more
499   * efficient.
500   *
501   * @throws IndexOutOfBoundsException if {@code fromIndex < 0}, {@code toIndex > array.length}, or
502   *     {@code toIndex > fromIndex}
503   * @since 23.1
504   */
505  public static void reverse(int[] array, int fromIndex, int toIndex) {
506    checkNotNull(array);
507    checkPositionIndexes(fromIndex, toIndex, array.length);
508    for (int i = fromIndex, j = toIndex - 1; i < j; i++, j--) {
509      int tmp = array[i];
510      array[i] = array[j];
511      array[j] = tmp;
512    }
513  }
514
515  /**
516   * Performs a right rotation of {@code array} of "distance" places, so that the first element is
517   * moved to index "distance", and the element at index {@code i} ends up at index {@code (distance
518   * + i) mod array.length}. This is equivalent to {@code Collections.rotate(Ints.asList(array),
519   * distance)}, but is considerably faster and avoids allocation and garbage collection.
520   *
521   * <p>The provided "distance" may be negative, which will rotate left.
522   *
523   * @since NEXT
524   */
525  public static void rotate(int[] array, int distance) {
526    rotate(array, distance, 0, array.length);
527  }
528
529  /**
530   * Performs a right rotation of {@code array} between {@code fromIndex} inclusive and {@code
531   * toIndex} exclusive. This is equivalent to {@code
532   * Collections.rotate(Ints.asList(array).subList(fromIndex, toIndex), distance)}, but is
533   * considerably faster and avoids allocations and garbage collection.
534   *
535   * <p>The provided "distance" may be negative, which will rotate left.
536   *
537   * @throws IndexOutOfBoundsException if {@code fromIndex < 0}, {@code toIndex > array.length}, or
538   *     {@code toIndex > fromIndex}
539   * @since NEXT
540   */
541  public static void rotate(int[] array, int distance, int fromIndex, int toIndex) {
542    // There are several well-known algorithms for rotating part of an array (or, equivalently,
543    // exchanging two blocks of memory). This classic text by Gries and Mills mentions several:
544    // https://ecommons.cornell.edu/bitstream/handle/1813/6292/81-452.pdf.
545    // (1) "Reversal", the one we have here.
546    // (2) "Dolphin". If we're rotating an array a of size n by a distance of d, then element a[0]
547    //     ends up at a[d], which in turn ends up at a[2d], and so on until we get back to a[0].
548    //     (All indices taken mod n.) If d and n are mutually prime, all elements will have been
549    //     moved at that point. Otherwise, we can rotate the cycle a[1], a[1 + d], a[1 + 2d], etc,
550    //     then a[2] etc, and so on until we have rotated all elements. There are gcd(d, n) cycles
551    //     in all.
552    // (3) "Successive". We can consider that we are exchanging a block of size d (a[0..d-1]) with a
553    //     block of size n-d (a[d..n-1]), where in general these blocks have different sizes. If we
554    //     imagine a line separating the first block from the second, we can proceed by exchanging
555    //     the smaller of these blocks with the far end of the other one. That leaves us with a
556    //     smaller version of the same problem.
557    //     Say we are rotating abcdefgh by 5. We start with abcde|fgh. The smaller block is [fgh]:
558    //     [abc]de|[fgh] -> [fgh]de|[abc]. Now [fgh] is in the right place, but we need to swap [de]
559    //     with [abc]: fgh[de]|a[bc] -> fgh[bc]|a[de]. Now we need to swap [a] with [bc]:
560    //     fgh[b]c|[a]de -> fgh[a]c|[b]de. Finally we need to swap [c] with [b]:
561    //     fgha[c]|[b]de -> fgha[b]|[c]de. Because these two blocks are the same size, we are done.
562    // The Dolphin algorithm is attractive because it does the fewest array reads and writes: each
563    // array slot is read and written exactly once. However, it can have very poor memory locality:
564    // benchmarking shows it can take 7 times longer than the other two in some cases. The other two
565    // do n swaps, minus a delta (0 or 2 for Reversal, gcd(d, n) for Successive), so that's about
566    // twice as many reads and writes. But benchmarking shows that they usually perform better than
567    // Dolphin. Reversal is about as good as Successive on average, and it is much simpler,
568    // especially since we already have a `reverse` method.
569    checkNotNull(array);
570    checkPositionIndexes(fromIndex, toIndex, array.length);
571    if (array.length <= 1) {
572      return;
573    }
574
575    int length = toIndex - fromIndex;
576    // Obtain m = (-distance mod length), a non-negative value less than "length". This is how many
577    // places left to rotate.
578    int m = -distance % length;
579    m = (m < 0) ? m + length : m;
580    // The current index of what will become the first element of the rotated section.
581    int newFirstIndex = m + fromIndex;
582    if (newFirstIndex == fromIndex) {
583      return;
584    }
585
586    reverse(array, fromIndex, newFirstIndex);
587    reverse(array, newFirstIndex, toIndex);
588    reverse(array, fromIndex, toIndex);
589  }
590
591  /**
592   * Returns an array containing each value of {@code collection}, converted to a {@code int} value
593   * in the manner of {@link Number#intValue}.
594   *
595   * <p>Elements are copied from the argument collection as if by {@code collection.toArray()}.
596   * Calling this method is as thread-safe as calling that method.
597   *
598   * @param collection a collection of {@code Number} instances
599   * @return an array containing the same values as {@code collection}, in the same order, converted
600   *     to primitives
601   * @throws NullPointerException if {@code collection} or any of its elements is null
602   * @since 1.0 (parameter was {@code Collection<Integer>} before 12.0)
603   */
604  public static int[] toArray(Collection<? extends Number> collection) {
605    if (collection instanceof IntArrayAsList) {
606      return ((IntArrayAsList) collection).toIntArray();
607    }
608
609    Object[] boxedArray = collection.toArray();
610    int len = boxedArray.length;
611    int[] array = new int[len];
612    for (int i = 0; i < len; i++) {
613      // checkNotNull for GWT (do not optimize)
614      array[i] = ((Number) checkNotNull(boxedArray[i])).intValue();
615    }
616    return array;
617  }
618
619  /**
620   * Returns a fixed-size list backed by the specified array, similar to {@link
621   * Arrays#asList(Object[])}. The list supports {@link List#set(int, Object)}, but any attempt to
622   * set a value to {@code null} will result in a {@link NullPointerException}.
623   *
624   * <p>The returned list maintains the values, but not the identities, of {@code Integer} objects
625   * written to or read from it. For example, whether {@code list.get(0) == list.get(0)} is true for
626   * the returned list is unspecified.
627   *
628   * <p>The returned list is serializable.
629   *
630   * <p><b>Note:</b> when possible, you should represent your data as an {@link ImmutableIntArray}
631   * instead, which has an {@link ImmutableIntArray#asList asList} view.
632   *
633   * @param backingArray the array to back the list
634   * @return a list view of the array
635   */
636  public static List<Integer> asList(int... backingArray) {
637    if (backingArray.length == 0) {
638      return Collections.emptyList();
639    }
640    return new IntArrayAsList(backingArray);
641  }
642
643  @GwtCompatible
644  private static class IntArrayAsList extends AbstractList<Integer>
645      implements RandomAccess, Serializable {
646    final int[] array;
647    final int start;
648    final int end;
649
650    IntArrayAsList(int[] array) {
651      this(array, 0, array.length);
652    }
653
654    IntArrayAsList(int[] array, int start, int end) {
655      this.array = array;
656      this.start = start;
657      this.end = end;
658    }
659
660    @Override
661    public int size() {
662      return end - start;
663    }
664
665    @Override
666    public boolean isEmpty() {
667      return false;
668    }
669
670    @Override
671    public Integer get(int index) {
672      checkElementIndex(index, size());
673      return array[start + index];
674    }
675
676    @Override
677    public Spliterator.OfInt spliterator() {
678      return Spliterators.spliterator(array, start, end, 0);
679    }
680
681    @Override
682    public boolean contains(@CheckForNull Object target) {
683      // Overridden to prevent a ton of boxing
684      return (target instanceof Integer) && Ints.indexOf(array, (Integer) target, start, end) != -1;
685    }
686
687    @Override
688    public int indexOf(@CheckForNull Object target) {
689      // Overridden to prevent a ton of boxing
690      if (target instanceof Integer) {
691        int i = Ints.indexOf(array, (Integer) target, start, end);
692        if (i >= 0) {
693          return i - start;
694        }
695      }
696      return -1;
697    }
698
699    @Override
700    public int lastIndexOf(@CheckForNull Object target) {
701      // Overridden to prevent a ton of boxing
702      if (target instanceof Integer) {
703        int i = Ints.lastIndexOf(array, (Integer) target, start, end);
704        if (i >= 0) {
705          return i - start;
706        }
707      }
708      return -1;
709    }
710
711    @Override
712    public Integer set(int index, Integer element) {
713      checkElementIndex(index, size());
714      int oldValue = array[start + index];
715      // checkNotNull for GWT (do not optimize)
716      array[start + index] = checkNotNull(element);
717      return oldValue;
718    }
719
720    @Override
721    public List<Integer> subList(int fromIndex, int toIndex) {
722      int size = size();
723      checkPositionIndexes(fromIndex, toIndex, size);
724      if (fromIndex == toIndex) {
725        return Collections.emptyList();
726      }
727      return new IntArrayAsList(array, start + fromIndex, start + toIndex);
728    }
729
730    @Override
731    public boolean equals(@CheckForNull Object object) {
732      if (object == this) {
733        return true;
734      }
735      if (object instanceof IntArrayAsList) {
736        IntArrayAsList that = (IntArrayAsList) object;
737        int size = size();
738        if (that.size() != size) {
739          return false;
740        }
741        for (int i = 0; i < size; i++) {
742          if (array[start + i] != that.array[that.start + i]) {
743            return false;
744          }
745        }
746        return true;
747      }
748      return super.equals(object);
749    }
750
751    @Override
752    public int hashCode() {
753      int result = 1;
754      for (int i = start; i < end; i++) {
755        result = 31 * result + Ints.hashCode(array[i]);
756      }
757      return result;
758    }
759
760    @Override
761    public String toString() {
762      StringBuilder builder = new StringBuilder(size() * 5);
763      builder.append('[').append(array[start]);
764      for (int i = start + 1; i < end; i++) {
765        builder.append(", ").append(array[i]);
766      }
767      return builder.append(']').toString();
768    }
769
770    int[] toIntArray() {
771      return Arrays.copyOfRange(array, start, end);
772    }
773
774    private static final long serialVersionUID = 0;
775  }
776
777  /**
778   * Parses the specified string as a signed decimal integer value. The ASCII character {@code '-'}
779   * (<code>'&#92;u002D'</code>) is recognized as the minus sign.
780   *
781   * <p>Unlike {@link Integer#parseInt(String)}, this method returns {@code null} instead of
782   * throwing an exception if parsing fails. Additionally, this method only accepts ASCII digits,
783   * and returns {@code null} if non-ASCII digits are present in the string.
784   *
785   * <p>Note that strings prefixed with ASCII {@code '+'} are rejected, even under JDK 7, despite
786   * the change to {@link Integer#parseInt(String)} for that version.
787   *
788   * @param string the string representation of an integer value
789   * @return the integer value represented by {@code string}, or {@code null} if {@code string} has
790   *     a length of zero or cannot be parsed as an integer value
791   * @throws NullPointerException if {@code string} is {@code null}
792   * @since 11.0
793   */
794  @Beta
795  @CheckForNull
796  public static Integer tryParse(String string) {
797    return tryParse(string, 10);
798  }
799
800  /**
801   * Parses the specified string as a signed integer value using the specified radix. The ASCII
802   * character {@code '-'} (<code>'&#92;u002D'</code>) is recognized as the minus sign.
803   *
804   * <p>Unlike {@link Integer#parseInt(String, int)}, this method returns {@code null} instead of
805   * throwing an exception if parsing fails. Additionally, this method only accepts ASCII digits,
806   * and returns {@code null} if non-ASCII digits are present in the string.
807   *
808   * <p>Note that strings prefixed with ASCII {@code '+'} are rejected, even under JDK 7, despite
809   * the change to {@link Integer#parseInt(String, int)} for that version.
810   *
811   * @param string the string representation of an integer value
812   * @param radix the radix to use when parsing
813   * @return the integer value represented by {@code string} using {@code radix}, or {@code null} if
814   *     {@code string} has a length of zero or cannot be parsed as an integer value
815   * @throws IllegalArgumentException if {@code radix < Character.MIN_RADIX} or {@code radix >
816   *     Character.MAX_RADIX}
817   * @throws NullPointerException if {@code string} is {@code null}
818   * @since 19.0
819   */
820  @Beta
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}