Class Doubles
- java.lang.Object
-
- com.google.common.primitives.Doubles
-
@GwtCompatible(emulated=true) public final class Doubles extends java.lang.Object
Static utility methods pertaining todouble
primitives, that are not already found in eitherDouble
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 primitivedouble
value.
-
Method Summary
All Methods Static Methods Concrete Methods Modifier and Type Method Description static java.util.List<java.lang.Double>
asList(double... backingArray)
Returns a fixed-size list backed by the specified array, similar toArrays.asList(Object[])
.static int
compare(double a, double b)
Compares the two specifieddouble
values.static double[]
concat(double[]... arrays)
Returns the values from each provided array combined into a single array.static double
constrainToRange(double value, double min, double max)
Returns the value nearest tovalue
which is within the closed range[min..max]
.static boolean
contains(double[] array, double target)
Returnstrue
iftarget
is present as an element anywhere inarray
.static double[]
ensureCapacity(double[] array, int minLength, int padding)
Returns an array containing the same values asarray
, but guaranteed to be of a specified minimum length.static int
hashCode(double value)
Returns a hash code forvalue
; equal to the result of invoking((Double) value).hashCode()
.static int
indexOf(double[] array, double target)
Returns the index of the first appearance of the valuetarget
inarray
.static int
indexOf(double[] array, double[] target)
Returns the start position of the first occurrence of the specifiedtarget
withinarray
, or-1
if there is no such occurrence.static boolean
isFinite(double value)
Returnstrue
ifvalue
represents a real number.static java.lang.String
join(java.lang.String separator, double... array)
Returns a string containing the supplieddouble
values, converted to strings as specified byDouble.toString(double)
, and separated byseparator
.static int
lastIndexOf(double[] array, double target)
Returns the index of the last appearance of the valuetarget
inarray
.static java.util.Comparator<double[]>
lexicographicalComparator()
Returns a comparator that compares twodouble
arrays lexicographically.static double
max(double... array)
Returns the greatest value present inarray
, using the same rules of comparison asMath.max(double, double)
.static double
min(double... array)
Returns the least value present inarray
, using the same rules of comparison asMath.min(double, double)
.static void
reverse(double[] array)
Reverses the elements ofarray
.static void
reverse(double[] array, int fromIndex, int toIndex)
Reverses the elements ofarray
betweenfromIndex
inclusive andtoIndex
exclusive.static void
rotate(double[] 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(double[] array, int distance, int fromIndex, int toIndex)
Performs a right rotation ofarray
betweenfromIndex
inclusive andtoIndex
exclusive.static void
sortDescending(double[] array)
Sorts the elements ofarray
in descending order.static void
sortDescending(double[] array, int fromIndex, int toIndex)
Sorts the elements ofarray
betweenfromIndex
inclusive andtoIndex
exclusive in descending order.static Converter<java.lang.String,java.lang.Double>
stringConverter()
Returns a serializable converter object that converts between strings and doubles usingDouble.valueOf(java.lang.String)
andDouble.toString()
.static double[]
toArray(java.util.Collection<? extends java.lang.Number> collection)
Returns an array containing each value ofcollection
, converted to adouble
value in the manner ofNumber.doubleValue()
.static java.lang.Double
tryParse(java.lang.String string)
Parses the specified string as a double-precision floating point value.
-
-
-
Field Detail
-
BYTES
public static final int BYTES
The number of bytes required to represent a primitivedouble
value.Java 8+ users: use
Double.BYTES
instead.- Since:
- 10.0
- See Also:
- Constant Field Values
-
-
Method Detail
-
hashCode
public static int hashCode(double value)
Returns a hash code forvalue
; equal to the result of invoking((Double) value).hashCode()
.Java 8+ users: use
Double.hashCode(double)
instead.- Parameters:
value
- a primitivedouble
value- Returns:
- a hash code for the value
-
compare
@InlineMe(replacement="Double.compare(a, b)") public static int compare(double a, double b)
Compares the two specifieddouble
values. The sign of the value returned is the same as that of((Double) a).compareTo(b)
. As with that method,NaN
is treated as greater than all other values, and0.0 > -0.0
.Note: this method simply delegates to the JDK method
Double.compare(double, double)
. It is provided for consistency with the other primitive types, whose compare methods were not added to the JDK until JDK 7.- Parameters:
a
- the firstdouble
to compareb
- the seconddouble
to compare- Returns:
- a negative value if
a
is less thanb
; a positive value ifa
is greater thanb
; or zero if they are equal
-
isFinite
public static boolean isFinite(double value)
Returnstrue
ifvalue
represents a real number. This is equivalent to, but not necessarily implemented as,!(Double.isInfinite(value) || Double.isNaN(value))
.Java 8+ users: use
Double.isFinite(double)
instead.- Since:
- 10.0
-
contains
public static boolean contains(double[] array, double target)
Returnstrue
iftarget
is present as an element anywhere inarray
. Note that this always returnsfalse
whentarget
isNaN
.- Parameters:
array
- an array ofdouble
values, possibly emptytarget
- a primitivedouble
value- Returns:
true
ifarray[i] == target
for some value ofi
-
indexOf
public static int indexOf(double[] array, double target)
Returns the index of the first appearance of the valuetarget
inarray
. Note that this always returns-1
whentarget
isNaN
.- Parameters:
array
- an array ofdouble
values, possibly emptytarget
- a primitivedouble
value- Returns:
- the least index
i
for whicharray[i] == target
, or-1
if no such index exists.
-
indexOf
public static int indexOf(double[] array, double[] 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
.Note that this always returns
-1
whentarget
containsNaN
.- 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(double[] array, double target)
Returns the index of the last appearance of the valuetarget
inarray
. Note that this always returns-1
whentarget
isNaN
.- Parameters:
array
- an array ofdouble
values, possibly emptytarget
- a primitivedouble
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 double min(double... array)
Returns the least value present inarray
, using the same rules of comparison asMath.min(double, double)
.- Parameters:
array
- a nonempty array ofdouble
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
@GwtIncompatible("Available in GWT! Annotation is to avoid conflict with GWT specialization of base class.") public static double max(double... array)
Returns the greatest value present inarray
, using the same rules of comparison asMath.max(double, double)
.- Parameters:
array
- a nonempty array ofdouble
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 double constrainToRange(double value, double min, double 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.- Parameters:
value
- thedouble
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 double[] concat(double[]... arrays)
Returns the values from each provided array combined into a single array. For example,concat(new double[] {a, b}, new double[] {}, new double[] {c}
returns the array{a, b, c}
.- Parameters:
arrays
- zero or moredouble
arrays- Returns:
- a single array containing all the values from the source arrays, in order
- Throws:
java.lang.IllegalArgumentException
- if the total number of elements inarrays
does not fit in anint
-
stringConverter
public static Converter<java.lang.String,java.lang.Double> stringConverter()
Returns a serializable converter object that converts between strings and doubles usingDouble.valueOf(java.lang.String)
andDouble.toString()
.- Since:
- 16.0
-
ensureCapacity
public static double[] ensureCapacity(double[] 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, double... array)
Returns a string containing the supplieddouble
values, converted to strings as specified byDouble.toString(double)
, and separated byseparator
. For example,join("-", 1.0, 2.0, 3.0)
returns the string"1.0-2.0-3.0"
.Note that
Double.toString(double)
formatsdouble
differently in GWT sometimes. In the previous example, it 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 ofdouble
values, possibly empty
-
lexicographicalComparator
public static java.util.Comparator<double[]> lexicographicalComparator()
Returns a comparator that compares twodouble
arrays lexicographically. That is, it compares, usingcompare(double, double)
), 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.0] < [1.0, 2.0] < [2.0]
.The returned comparator is inconsistent with
Object.equals(Object)
(since arrays support only identity equality), but it is consistent withArrays.equals(double[], double[])
.- Since:
- 2.0
-
sortDescending
public static void sortDescending(double[] array)
Sorts the elements ofarray
in descending order.Note that this method uses the total order imposed by
Double.compare(double, double)
, which treats all NaN values as equal and 0.0 as greater than -0.0.- Since:
- 23.1
-
sortDescending
public static void sortDescending(double[] array, int fromIndex, int toIndex)
Sorts the elements ofarray
betweenfromIndex
inclusive andtoIndex
exclusive in descending order.Note that this method uses the total order imposed by
Double.compare(double, double)
, which treats all NaN values as equal and 0.0 as greater than -0.0.- Since:
- 23.1
-
reverse
public static void reverse(double[] array)
Reverses the elements ofarray
. This is equivalent toCollections.reverse(Doubles.asList(array))
, but is likely to be more efficient.- Since:
- 23.1
-
reverse
public static void reverse(double[] array, int fromIndex, int toIndex)
Reverses the elements ofarray
betweenfromIndex
inclusive andtoIndex
exclusive. This is equivalent toCollections.reverse(Doubles.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(double[] 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(Bytes.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(double[] array, int distance, int fromIndex, int toIndex)
Performs a right rotation ofarray
betweenfromIndex
inclusive andtoIndex
exclusive. This is equivalent toCollections.rotate(Bytes.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
-
toArray
public static double[] toArray(java.util.Collection<? extends java.lang.Number> collection)
Returns an array containing each value ofcollection
, converted to adouble
value in the manner ofNumber.doubleValue()
.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:
java.lang.NullPointerException
- ifcollection
or any of its elements is null- Since:
- 1.0 (parameter was
Collection<Double>
before 12.0)
-
asList
public static java.util.List<java.lang.Double> asList(double... 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
Double
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 may have unexpected behavior if it contains
NaN
, or ifNaN
is used as a parameter to any of its methods.The returned list is serializable.
Note: when possible, you should represent your data as an
ImmutableDoubleArray
instead, which has anasList
view.- Parameters:
backingArray
- the array to back the list- Returns:
- a list view of the array
-
tryParse
@GwtIncompatible @CheckForNull public static java.lang.Double tryParse(java.lang.String string)
Parses the specified string as a double-precision floating point value. The ASCII character'-'
('\u002D'
) is recognized as the minus sign.Unlike
Double.parseDouble(String)
, this method returnsnull
instead of throwing an exception if parsing fails. Valid inputs are exactly those accepted byDouble.valueOf(String)
, except that leading and trailing whitespace is not permitted.This implementation is likely to be faster than
Double.parseDouble
if many failures are expected.- Parameters:
string
- the string representation of adouble
value- Returns:
- the floating point value represented by
string
, ornull
ifstring
has a length of zero or cannot be parsed as adouble
value - Throws:
java.lang.NullPointerException
- ifstring
isnull
- Since:
- 14.0
-
-