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