Class Chars
- java.lang.Object
-
- com.google.common.primitives.Chars
-
@GwtCompatible(emulated=true) public final class Chars extends java.lang.Object
Static utility methods pertaining tochar
primitives, that are not already found in eitherCharacter
orArrays
.All the operations in this class treat
char
values strictly numerically; they are neither Unicode-aware nor locale-dependent.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 primitivechar
value.
-
Method Summary
All Methods Static Methods Concrete Methods Modifier and Type Method Description static java.util.List<java.lang.Character>
asList(char... backingArray)
Returns a fixed-size list backed by the specified array, similar toArrays.asList(Object[])
.static char
checkedCast(long value)
Returns thechar
value that is equal tovalue
, if possible.static int
compare(char a, char b)
Compares the two specifiedchar
values.static char[]
concat(char[]... arrays)
Returns the values from each provided array combined into a single array.static char
constrainToRange(char value, char min, char max)
Returns the value nearest tovalue
which is within the closed range[min..max]
.static boolean
contains(char[] array, char target)
Returnstrue
iftarget
is present as an element anywhere inarray
.static char[]
ensureCapacity(char[] array, int minLength, int padding)
Returns an array containing the same values asarray
, but guaranteed to be of a specified minimum length.static char
fromByteArray(byte[] bytes)
Returns thechar
value whose big-endian representation is stored in the first 2 bytes ofbytes
; equivalent toByteBuffer.wrap(bytes).getChar()
.static char
fromBytes(byte b1, byte b2)
Returns thechar
value whose byte representation is the given 2 bytes, in big-endian order; equivalent toChars.fromByteArray(new byte[] {b1, b2})
.static int
hashCode(char value)
Returns a hash code forvalue
; equal to the result of invoking((Character) value).hashCode()
.static int
indexOf(char[] array, char target)
Returns the index of the first appearance of the valuetarget
inarray
.static int
indexOf(char[] array, char[] target)
Returns the start position of the first occurrence of the specifiedtarget
withinarray
, or-1
if there is no such occurrence.static java.lang.String
join(java.lang.String separator, char... array)
Returns a string containing the suppliedchar
values separated byseparator
.static int
lastIndexOf(char[] array, char target)
Returns the index of the last appearance of the valuetarget
inarray
.static java.util.Comparator<char[]>
lexicographicalComparator()
Returns a comparator that compares twochar
arrays lexicographically; not advisable for sorting user-visible strings as the ordering may not match the conventions of the user's locale.static char
max(char... array)
Returns the greatest value present inarray
.static char
min(char... array)
Returns the least value present inarray
.static void
reverse(char[] array)
Reverses the elements ofarray
.static void
reverse(char[] array, int fromIndex, int toIndex)
Reverses the elements ofarray
betweenfromIndex
inclusive andtoIndex
exclusive.static void
rotate(char[] 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(char[] array, int distance, int fromIndex, int toIndex)
Performs a right rotation ofarray
betweenfromIndex
inclusive andtoIndex
exclusive.static char
saturatedCast(long value)
Returns thechar
nearest in value tovalue
.static void
sortDescending(char[] array)
Sorts the elements ofarray
in descending order.static void
sortDescending(char[] array, int fromIndex, int toIndex)
Sorts the elements ofarray
betweenfromIndex
inclusive andtoIndex
exclusive in descending order.static char[]
toArray(java.util.Collection<java.lang.Character> collection)
Copies a collection ofCharacter
instances into a new array of primitivechar
values.static byte[]
toByteArray(char value)
Returns a big-endian representation ofvalue
in a 2-element byte array; equivalent toByteBuffer.allocate(2).putChar(value).array()
.
-
-
-
Field Detail
-
BYTES
public static final int BYTES
The number of bytes required to represent a primitivechar
value.Java 8+ users: use
Character.BYTES
instead.- See Also:
- Constant Field Values
-
-
Method Detail
-
hashCode
public static int hashCode(char value)
Returns a hash code forvalue
; equal to the result of invoking((Character) value).hashCode()
.Java 8+ users: use
Character.hashCode(char)
instead.- Parameters:
value
- a primitivechar
value- Returns:
- a hash code for the value
-
checkedCast
public static char checkedCast(long value)
Returns thechar
value that is equal tovalue
, if possible.- Parameters:
value
- any value in the range of thechar
type- Returns:
- the
char
value that equalsvalue
- Throws:
java.lang.IllegalArgumentException
- ifvalue
is greater thanCharacter.MAX_VALUE
or less thanCharacter.MIN_VALUE
-
saturatedCast
public static char saturatedCast(long value)
Returns thechar
nearest in value tovalue
.- Parameters:
value
- anylong
value- Returns:
- the same value cast to
char
if it is in the range of thechar
type,Character.MAX_VALUE
if it is too large, orCharacter.MIN_VALUE
if it is too small
-
compare
@InlineMe(replacement="Character.compare(a, b)") public static int compare(char a, char b)
Compares the two specifiedchar
values. The sign of the value returned is the same as that of((Character) a).compareTo(b)
.Note: this method is now unnecessary and should be treated as deprecated; use the equivalent
Character.compare(char, char)
method instead.- Parameters:
a
- the firstchar
to compareb
- the secondchar
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(char[] array, char target)
Returnstrue
iftarget
is present as an element anywhere inarray
.- Parameters:
array
- an array ofchar
values, possibly emptytarget
- a primitivechar
value- Returns:
true
ifarray[i] == target
for some value ofi
-
indexOf
public static int indexOf(char[] array, char target)
Returns the index of the first appearance of the valuetarget
inarray
.- Parameters:
array
- an array ofchar
values, possibly emptytarget
- a primitivechar
value- Returns:
- the least index
i
for whicharray[i] == target
, or-1
if no such index exists.
-
indexOf
public static int indexOf(char[] array, char[] 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(char[] array, char target)
Returns the index of the last appearance of the valuetarget
inarray
.- Parameters:
array
- an array ofchar
values, possibly emptytarget
- a primitivechar
value- Returns:
- the greatest index
i
for whicharray[i] == target
, or-1
if no such index exists.
-
min
public static char min(char... array)
Returns the least value present inarray
.- Parameters:
array
- a nonempty array ofchar
values- Returns:
- the value present in
array
that is less than or equal to every other value in the array - Throws:
java.lang.IllegalArgumentException
- ifarray
is empty
-
max
public static char max(char... array)
Returns the greatest value present inarray
.- Parameters:
array
- a nonempty array ofchar
values- Returns:
- the value present in
array
that is greater than or equal to every other value in the array - Throws:
java.lang.IllegalArgumentException
- ifarray
is empty
-
constrainToRange
public static char constrainToRange(char value, char min, char 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.- Parameters:
value
- thechar
value to constrainmin
- the lower bound (inclusive) of the range to constrainvalue
tomax
- the upper bound (inclusive) of the range to constrainvalue
to- Throws:
java.lang.IllegalArgumentException
- ifmin > max
- Since:
- 21.0
-
concat
public static char[] concat(char[]... arrays)
Returns the values from each provided array combined into a single array. For example,concat(new char[] {a, b}, new char[] {}, new char[] {c}
returns the array{a, b, c}
.- Parameters:
arrays
- zero or morechar
arrays- Returns:
- a single array containing all the values from the source arrays, in order
-
toByteArray
@GwtIncompatible public static byte[] toByteArray(char value)
Returns a big-endian representation ofvalue
in a 2-element byte array; equivalent toByteBuffer.allocate(2).putChar(value).array()
. For example, the input value'\\u5432'
would yield the byte array{0x54, 0x32}
.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
@GwtIncompatible public static char fromByteArray(byte[] bytes)
Returns thechar
value whose big-endian representation is stored in the first 2 bytes ofbytes
; equivalent toByteBuffer.wrap(bytes).getChar()
. For example, the input byte array{0x54, 0x32}
would yield thechar
value'\\u5432'
.Arguably, it's preferable to use
ByteBuffer
; that library exposes much more flexibility at little cost in readability.- Throws:
java.lang.IllegalArgumentException
- ifbytes
has fewer than 2 elements
-
fromBytes
@GwtIncompatible public static char fromBytes(byte b1, byte b2)
Returns thechar
value whose byte representation is the given 2 bytes, in big-endian order; equivalent toChars.fromByteArray(new byte[] {b1, b2})
.- Since:
- 7.0
-
ensureCapacity
public static char[] ensureCapacity(char[] 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:
java.lang.IllegalArgumentException
- ifminLength
orpadding
is negative
-
join
public static java.lang.String join(java.lang.String separator, char... array)
Returns a string containing the suppliedchar
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 ofchar
values, possibly empty
-
lexicographicalComparator
public static java.util.Comparator<char[]> lexicographicalComparator()
Returns a comparator that compares twochar
arrays lexicographically; not advisable for sorting user-visible strings as the ordering may not match the conventions of the user's locale. That is, it compares, usingcompare(char, char)
), 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,[] < ['a'] < ['a', 'b'] < ['b']
.The returned comparator is inconsistent with
Object.equals(Object)
(since arrays support only identity equality), but it is consistent withArrays.equals(char[], char[])
.- Since:
- 2.0
-
toArray
public static char[] toArray(java.util.Collection<java.lang.Character> collection)
Copies a collection ofCharacter
instances into a new array of primitivechar
values.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 ofCharacter
objects- Returns:
- an array containing the same values as
collection
, in the same order, converted to primitives - Throws:
java.lang.NullPointerException
- ifcollection
or any of its elements is null
-
sortDescending
public static void sortDescending(char[] array)
Sorts the elements ofarray
in descending order.- Since:
- 23.1
-
sortDescending
public static void sortDescending(char[] array, int fromIndex, int toIndex)
Sorts the elements ofarray
betweenfromIndex
inclusive andtoIndex
exclusive in descending order.- Since:
- 23.1
-
reverse
public static void reverse(char[] array)
Reverses the elements ofarray
. This is equivalent toCollections.reverse(Chars.asList(array))
, but is likely to be more efficient.- Since:
- 23.1
-
reverse
public static void reverse(char[] array, int fromIndex, int toIndex)
Reverses the elements ofarray
betweenfromIndex
inclusive andtoIndex
exclusive. This is equivalent toCollections.reverse(Chars.asList(array).subList(fromIndex, toIndex))
, but is likely to be more efficient.- Throws:
java.lang.IndexOutOfBoundsException
- iffromIndex < 0
,toIndex > array.length
, ortoIndex > fromIndex
- Since:
- 23.1
-
rotate
public static void rotate(char[] 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(Chars.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(char[] array, int distance, int fromIndex, int toIndex)
Performs a right rotation ofarray
betweenfromIndex
inclusive andtoIndex
exclusive. This is equivalent toCollections.rotate(Chars.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:
java.lang.IndexOutOfBoundsException
- iffromIndex < 0
,toIndex > array.length
, ortoIndex > fromIndex
- Since:
- 32.0.0
-
asList
public static java.util.List<java.lang.Character> asList(char... 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
Character
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.
- Parameters:
backingArray
- the array to back the list- Returns:
- a list view of the array
-
-