Class Ints
- java.lang.Object
-
- com.google.common.primitives.Ints
-
@GwtCompatible(emulated=true) public final class Ints extends Object
Static utility methods pertaining toint
primitives, that are not already found in eitherInteger
orArrays
.See the Guava User Guide article on primitive utilities.
- Since:
- 1.0
- Author:
- Kevin Bourrillion
-
-
Field Summary
Fields Modifier and Type Field Description static int
BYTES
The number of bytes required to represent a primitiveint
value.static int
MAX_POWER_OF_TWO
The largest power of two that can be represented as anint
.
-
Method Summary
All Methods Static Methods Concrete Methods Modifier and Type Method Description static List<Integer>
asList(int... backingArray)
Returns a fixed-size list backed by the specified array, similar toArrays.asList(Object[])
.static int
checkedCast(long value)
Returns theint
value that is equal tovalue
, if possible.static int
compare(int a, int b)
Compares the two specifiedint
values.static int[]
concat(int[]... arrays)
Returns the values from each provided array combined into a single array.static int
constrainToRange(int value, int min, int max)
Returns the value nearest tovalue
which is within the closed range[min..max]
.static boolean
contains(int[] array, int target)
Returnstrue
iftarget
is present as an element anywhere inarray
.static int[]
ensureCapacity(int[] array, int minLength, int padding)
Returns an array containing the same values asarray
, but guaranteed to be of a specified minimum length.static int
fromByteArray(byte[] bytes)
Returns theint
value whose big-endian representation is stored in the first 4 bytes ofbytes
; equivalent toByteBuffer.wrap(bytes).getInt()
.static int
fromBytes(byte b1, byte b2, byte b3, byte b4)
Returns theint
value whose byte representation is the given 4 bytes, in big-endian order; equivalent toInts.fromByteArray(new byte[] {b1, b2, b3, b4})
.static int
hashCode(int value)
Returns a hash code forvalue
; equal to the result of invoking((Integer) value).hashCode()
.static int
indexOf(int[] array, int target)
Returns the index of the first appearance of the valuetarget
inarray
.static int
indexOf(int[] array, int[] target)
Returns the start position of the first occurrence of the specifiedtarget
withinarray
, or-1
if there is no such occurrence.static String
join(String separator, int... array)
Returns a string containing the suppliedint
values separated byseparator
.static int
lastIndexOf(int[] array, int target)
Returns the index of the last appearance of the valuetarget
inarray
.static Comparator<int[]>
lexicographicalComparator()
Returns a comparator that compares twoint
arrays lexicographically.static int
max(int... array)
Returns the greatest value present inarray
.static int
min(int... array)
Returns the least value present inarray
.static void
reverse(int[] array)
Reverses the elements ofarray
.static void
reverse(int[] array, int fromIndex, int toIndex)
Reverses the elements ofarray
betweenfromIndex
inclusive andtoIndex
exclusive.static void
rotate(int[] array, int distance)
Performs a right rotation ofarray
of "distance" places, so that the first element is moved to index "distance", and the element at indexi
ends up at index(distance + i) mod array.length
.static void
rotate(int[] array, int distance, int fromIndex, int toIndex)
Performs a right rotation ofarray
betweenfromIndex
inclusive andtoIndex
exclusive.static int
saturatedCast(long value)
Returns theint
nearest in value tovalue
.static void
sortDescending(int[] array)
Sorts the elements ofarray
in descending order.static void
sortDescending(int[] array, int fromIndex, int toIndex)
Sorts the elements ofarray
betweenfromIndex
inclusive andtoIndex
exclusive in descending order.static Converter<String,Integer>
stringConverter()
Returns a serializable converter object that converts between strings and integers usingInteger.decode(java.lang.String)
andInteger.toString()
.static int[]
toArray(Collection<? extends Number> collection)
Returns an array containing each value ofcollection
, converted to aint
value in the manner ofNumber.intValue()
.static byte[]
toByteArray(int value)
Returns a big-endian representation ofvalue
in a 4-element byte array; equivalent toByteBuffer.allocate(4).putInt(value).array()
.static Integer
tryParse(String string)
Parses the specified string as a signed decimal integer value.static Integer
tryParse(String string, int radix)
Parses the specified string as a signed integer value using the specified radix.
-
-
-
Field Detail
-
BYTES
public static final int BYTES
The number of bytes required to represent a primitiveint
value.Java 8+ users: use
Integer.BYTES
instead.- See Also:
- Constant Field Values
-
MAX_POWER_OF_TWO
public static final int MAX_POWER_OF_TWO
The largest power of two that can be represented as anint
.- Since:
- 10.0
- See Also:
- Constant Field Values
-
-
Method Detail
-
hashCode
public static int hashCode(int value)
Returns a hash code forvalue
; equal to the result of invoking((Integer) value).hashCode()
.Java 8+ users: use
Integer.hashCode(int)
instead.- Parameters:
value
- a primitiveint
value- Returns:
- a hash code for the value
-
checkedCast
public static int checkedCast(long value)
Returns theint
value that is equal tovalue
, if possible.- Parameters:
value
- any value in the range of theint
type- Returns:
- the
int
value that equalsvalue
- Throws:
IllegalArgumentException
- ifvalue
is greater thanInteger.MAX_VALUE
or less thanInteger.MIN_VALUE
-
saturatedCast
public static int saturatedCast(long value)
Returns theint
nearest in value tovalue
.- Parameters:
value
- anylong
value- Returns:
- the same value cast to
int
if it is in the range of theint
type,Integer.MAX_VALUE
if it is too large, orInteger.MIN_VALUE
if it is too small
-
compare
@InlineMe(replacement="Integer.compare(a, b)") public static int compare(int a, int b)
Compares the two specifiedint
values. The sign of the value returned is the same as that of((Integer) a).compareTo(b)
.Note: this method is now unnecessary and should be treated as deprecated; use the equivalent
Integer.compare(int, int)
method instead.- Parameters:
a
- the firstint
to compareb
- the secondint
to compare- Returns:
- a negative value if
a
is less thanb
; a positive value ifa
is greater thanb
; or zero if they are equal
-
contains
public static boolean contains(int[] array, int target)
Returnstrue
iftarget
is present as an element anywhere inarray
.- Parameters:
array
- an array ofint
values, possibly emptytarget
- a primitiveint
value- Returns:
true
ifarray[i] == target
for some value ofi
-
indexOf
public static int indexOf(int[] array, int target)
Returns the index of the first appearance of the valuetarget
inarray
.- Parameters:
array
- an array ofint
values, possibly emptytarget
- a primitiveint
value- Returns:
- the least index
i
for whicharray[i] == target
, or-1
if no such index exists.
-
indexOf
public static int indexOf(int[] array, int[] target)
Returns the start position of the first occurrence of the specifiedtarget
withinarray
, or-1
if there is no such occurrence.More formally, returns the lowest index
i
such thatArrays.copyOfRange(array, i, i + target.length)
contains exactly the same elements astarget
.- Parameters:
array
- the array to search for the sequencetarget
target
- the array to search for as a sub-sequence ofarray
-
lastIndexOf
public static int lastIndexOf(int[] array, int target)
Returns the index of the last appearance of the valuetarget
inarray
.- Parameters:
array
- an array ofint
values, possibly emptytarget
- a primitiveint
value- Returns:
- the greatest index
i
for whicharray[i] == target
, or-1
if no such index exists.
-
min
@GwtIncompatible("Available in GWT! Annotation is to avoid conflict with GWT specialization of base class.") public static int min(int... array)
Returns the least value present inarray
.- Parameters:
array
- a nonempty array ofint
values- Returns:
- the value present in
array
that is less than or equal to every other value in the array - Throws:
IllegalArgumentException
- ifarray
is empty
-
max
@GwtIncompatible("Available in GWT! Annotation is to avoid conflict with GWT specialization of base class.") public static int max(int... array)
Returns the greatest value present inarray
.- Parameters:
array
- a nonempty array ofint
values- Returns:
- the value present in
array
that is greater than or equal to every other value in the array - Throws:
IllegalArgumentException
- ifarray
is empty
-
constrainToRange
public static int constrainToRange(int value, int min, int max)
Returns the value nearest tovalue
which is within the closed range[min..max]
.If
value
is within the range[min..max]
,value
is returned unchanged. Ifvalue
is less thanmin
,min
is returned, and ifvalue
is greater thanmax
,max
is returned.Java 21+ users: Use
Math.clamp
instead. Note that that method is capable of constraining along
input to anint
range.- Parameters:
value
- theint
value to constrainmin
- the lower bound (inclusive) of the range to constrainvalue
tomax
- the upper bound (inclusive) of the range to constrainvalue
to- Throws:
IllegalArgumentException
- ifmin > max
- Since:
- 21.0
-
concat
public static int[] concat(int[]... arrays)
Returns the values from each provided array combined into a single array. For example,concat(new int[] {a, b}, new int[] {}, new int[] {c}
returns the array{a, b, c}
.- Parameters:
arrays
- zero or moreint
arrays- Returns:
- a single array containing all the values from the source arrays, in order
- Throws:
IllegalArgumentException
- if the total number of elements inarrays
does not fit in anint
-
toByteArray
public static byte[] toByteArray(int value)
Returns a big-endian representation ofvalue
in a 4-element byte array; equivalent toByteBuffer.allocate(4).putInt(value).array()
. For example, the input value0x12131415
would yield the byte array{0x12, 0x13, 0x14, 0x15}
.If you need to convert and concatenate several values (possibly even of different types), use a shared
ByteBuffer
instance, or useByteStreams.newDataOutput()
to get a growable buffer.
-
fromByteArray
public static int fromByteArray(byte[] bytes)
Returns theint
value whose big-endian representation is stored in the first 4 bytes ofbytes
; equivalent toByteBuffer.wrap(bytes).getInt()
. For example, the input byte array{0x12, 0x13, 0x14, 0x15, 0x33}
would yield theint
value0x12131415
.Arguably, it's preferable to use
ByteBuffer
; that library exposes much more flexibility at little cost in readability.- Throws:
IllegalArgumentException
- ifbytes
has fewer than 4 elements
-
fromBytes
public static int fromBytes(byte b1, byte b2, byte b3, byte b4)
Returns theint
value whose byte representation is the given 4 bytes, in big-endian order; equivalent toInts.fromByteArray(new byte[] {b1, b2, b3, b4})
.- Since:
- 7.0
-
stringConverter
public static Converter<String,Integer> stringConverter()
Returns a serializable converter object that converts between strings and integers usingInteger.decode(java.lang.String)
andInteger.toString()
. The returned converter throwsNumberFormatException
if the input string is invalid.Warning: please see
Integer.decode(java.lang.String)
to understand exactly how strings are parsed. For example, the string"0123"
is treated as octal and converted to the value83
.- Since:
- 16.0
-
ensureCapacity
public static int[] ensureCapacity(int[] array, int minLength, int padding)
Returns an array containing the same values asarray
, but guaranteed to be of a specified minimum length. Ifarray
already has a length of at leastminLength
, it is returned directly. Otherwise, a new array of sizeminLength + padding
is returned, containing the values ofarray
, and zeroes in the remaining places.- Parameters:
array
- the source arrayminLength
- the minimum length the returned array must guaranteepadding
- an extra amount to "grow" the array by if growth is necessary- Returns:
- an array containing the values of
array
, with guaranteed minimum lengthminLength
- Throws:
IllegalArgumentException
- ifminLength
orpadding
is negative
-
join
public static String join(String separator, int... array)
Returns a string containing the suppliedint
values separated byseparator
. For example,join("-", 1, 2, 3)
returns the string"1-2-3"
.- Parameters:
separator
- the text that should appear between consecutive values in the resulting string (but not at the start or end)array
- an array ofint
values, possibly empty
-
lexicographicalComparator
public static Comparator<int[]> lexicographicalComparator()
Returns a comparator that compares twoint
arrays lexicographically. That is, it compares, usingcompare(int, int)
), the first pair of values that follow any common prefix, or when one array is a prefix of the other, treats the shorter array as the lesser. For example,[] < [1] < [1, 2] < [2]
.The returned comparator is inconsistent with
Object.equals(Object)
(since arrays support only identity equality), but it is consistent withArrays.equals(int[], int[])
.- Since:
- 2.0
-
sortDescending
public static void sortDescending(int[] array)
Sorts the elements ofarray
in descending order.- Since:
- 23.1
-
sortDescending
public static void sortDescending(int[] array, int fromIndex, int toIndex)
Sorts the elements ofarray
betweenfromIndex
inclusive andtoIndex
exclusive in descending order.- Since:
- 23.1
-
reverse
public static void reverse(int[] array)
Reverses the elements ofarray
. This is equivalent toCollections.reverse(Ints.asList(array))
, but is likely to be more efficient.- Since:
- 23.1
-
reverse
public static void reverse(int[] array, int fromIndex, int toIndex)
Reverses the elements ofarray
betweenfromIndex
inclusive andtoIndex
exclusive. This is equivalent toCollections.reverse(Ints.asList(array).subList(fromIndex, toIndex))
, but is likely to be more efficient.- Throws:
IndexOutOfBoundsException
- iffromIndex < 0
,toIndex > array.length
, ortoIndex > fromIndex
- Since:
- 23.1
-
rotate
public static void rotate(int[] array, int distance)
Performs a right rotation ofarray
of "distance" places, so that the first element is moved to index "distance", and the element at indexi
ends up at index(distance + i) mod array.length
. This is equivalent toCollections.rotate(Ints.asList(array), distance)
, but is considerably faster and avoids allocation and garbage collection.The provided "distance" may be negative, which will rotate left.
- Since:
- 32.0.0
-
rotate
public static void rotate(int[] array, int distance, int fromIndex, int toIndex)
Performs a right rotation ofarray
betweenfromIndex
inclusive andtoIndex
exclusive. This is equivalent toCollections.rotate(Ints.asList(array).subList(fromIndex, toIndex), distance)
, but is considerably faster and avoids allocations and garbage collection.The provided "distance" may be negative, which will rotate left.
- Throws:
IndexOutOfBoundsException
- iffromIndex < 0
,toIndex > array.length
, ortoIndex > fromIndex
- Since:
- 32.0.0
-
toArray
public static int[] toArray(Collection<? extends Number> collection)
Returns an array containing each value ofcollection
, converted to aint
value in the manner ofNumber.intValue()
.Elements are copied from the argument collection as if by
collection.toArray()
. Calling this method is as thread-safe as calling that method.- Parameters:
collection
- a collection ofNumber
instances- Returns:
- an array containing the same values as
collection
, in the same order, converted to primitives - Throws:
NullPointerException
- ifcollection
or any of its elements is null- Since:
- 1.0 (parameter was
Collection<Integer>
before 12.0)
-
asList
public static List<Integer> asList(int... backingArray)
Returns a fixed-size list backed by the specified array, similar toArrays.asList(Object[])
. The list supportsList.set(int, Object)
, but any attempt to set a value tonull
will result in aNullPointerException
.The returned list maintains the values, but not the identities, of
Integer
objects written to or read from it. For example, whetherlist.get(0) == list.get(0)
is true for the returned list is unspecified.The returned list is serializable.
Note: when possible, you should represent your data as an
ImmutableIntArray
instead, which has anasList
view.- Parameters:
backingArray
- the array to back the list- Returns:
- a list view of the array
-
tryParse
@CheckForNull public static Integer tryParse(String string)
Parses the specified string as a signed decimal integer value. The ASCII character'-'
('\u002D'
) is recognized as the minus sign.Unlike
Integer.parseInt(String)
, this method returnsnull
instead of throwing an exception if parsing fails. Additionally, this method only accepts ASCII digits, and returnsnull
if non-ASCII digits are present in the string.Note that strings prefixed with ASCII
'+'
are rejected, even thoughInteger.parseInt(String)
accepts them.- Parameters:
string
- the string representation of an integer value- Returns:
- the integer value represented by
string
, ornull
ifstring
has a length of zero or cannot be parsed as an integer value - Throws:
NullPointerException
- ifstring
isnull
- Since:
- 11.0
-
tryParse
@CheckForNull public static Integer tryParse(String string, int radix)
Parses the specified string as a signed integer value using the specified radix. The ASCII character'-'
('\u002D'
) is recognized as the minus sign.Unlike
Integer.parseInt(String, int)
, this method returnsnull
instead of throwing an exception if parsing fails. Additionally, this method only accepts ASCII digits, and returnsnull
if non-ASCII digits are present in the string.Note that strings prefixed with ASCII
'+'
are rejected, even thoughInteger.parseInt(String)
accepts them.- Parameters:
string
- the string representation of an integer valueradix
- the radix to use when parsing- Returns:
- the integer value represented by
string
usingradix
, ornull
ifstring
has a length of zero or cannot be parsed as an integer value - Throws:
IllegalArgumentException
- ifradix < Character.MIN_RADIX
orradix > Character.MAX_RADIX
NullPointerException
- ifstring
isnull
- Since:
- 19.0
-
-