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