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