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