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