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