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; 021import static com.google.common.base.Strings.lenientFormat; 022import static java.lang.Double.parseDouble; 023import static java.lang.System.arraycopy; 024import static java.util.Arrays.sort; 025import static java.util.Collections.emptyList; 026 027import com.google.common.annotations.GwtCompatible; 028import com.google.common.annotations.GwtIncompatible; 029import com.google.common.annotations.J2ktIncompatible; 030import com.google.common.base.Converter; 031import com.google.errorprone.annotations.InlineMe; 032import java.io.Serializable; 033import java.util.AbstractList; 034import java.util.Arrays; 035import java.util.Collection; 036import java.util.Comparator; 037import java.util.List; 038import java.util.RandomAccess; 039import java.util.Spliterator; 040import java.util.Spliterators; 041import org.jspecify.annotations.Nullable; 042 043/** 044 * Static utility methods pertaining to {@code double} primitives, that are not already found in 045 * either {@link Double} or {@link Arrays}. 046 * 047 * <p>See the Guava User Guide article on <a 048 * href="https://github.com/google/guava/wiki/PrimitivesExplained">primitive utilities</a>. 049 * 050 * @author Kevin Bourrillion 051 * @since 1.0 052 */ 053@GwtCompatible 054public final class Doubles extends DoublesMethodsForWeb { 055 private Doubles() {} 056 057 /** 058 * The number of bytes required to represent a primitive {@code double} value. 059 * 060 * <p>Prefer {@link Double#BYTES} instead. 061 * 062 * @since 10.0 063 */ 064 public static final int BYTES = Double.BYTES; 065 066 /** 067 * Returns a hash code for {@code value}; obsolete alternative to {@link Double#hashCode(double)}. 068 * 069 * @param value a primitive {@code double} value 070 * @return a hash code for the value 071 */ 072 @InlineMe(replacement = "Double.hashCode(value)") 073 public static int hashCode(double value) { 074 return Double.hashCode(value); 075 } 076 077 /** 078 * Compares the two specified {@code double} values. The sign of the value returned is the same as 079 * that of <code>((Double) a).{@linkplain Double#compareTo compareTo}(b)</code>. As with that 080 * method, {@code NaN} is treated as greater than all other values, and {@code 0.0 > -0.0}. 081 * 082 * <p><b>Note:</b> this method simply delegates to the JDK method {@link Double#compare}. It is 083 * provided for consistency with the other primitive types, whose compare methods were not added 084 * to the JDK until JDK 7. 085 * 086 * @param a the first {@code double} to compare 087 * @param b the second {@code double} to compare 088 * @return a negative value if {@code a} is less than {@code b}; a positive value if {@code a} is 089 * greater than {@code b}; or zero if they are equal 090 */ 091 @InlineMe(replacement = "Double.compare(a, b)") 092 public static int compare(double a, double b) { 093 return Double.compare(a, b); 094 } 095 096 /** 097 * Returns {@code true} if {@code value} represents a real number. This is equivalent to, but not 098 * necessarily implemented as, {@code !(Double.isInfinite(value) || Double.isNaN(value))}. 099 * 100 * <p>Prefer {@link Double#isFinite(double)} instead. 101 * 102 * @since 10.0 103 */ 104 @InlineMe(replacement = "Double.isFinite(value)") 105 public static boolean isFinite(double value) { 106 return Double.isFinite(value); 107 } 108 109 /** 110 * Returns {@code true} if {@code target} is present as an element anywhere in {@code array}. Note 111 * that this always returns {@code false} when {@code target} is {@code NaN}. 112 * 113 * @param array an array of {@code double} values, possibly empty 114 * @param target a primitive {@code double} value 115 * @return {@code true} if {@code array[i] == target} for some value of {@code i} 116 */ 117 public static boolean contains(double[] array, double target) { 118 for (double value : array) { 119 if (value == target) { 120 return true; 121 } 122 } 123 return false; 124 } 125 126 /** 127 * Returns the index of the first appearance of the value {@code target} in {@code array}. Note 128 * that this always returns {@code -1} when {@code target} is {@code NaN}. 129 * 130 * @param array an array of {@code double} values, possibly empty 131 * @param target a primitive {@code double} value 132 * @return the least index {@code i} for which {@code array[i] == target}, or {@code -1} if no 133 * such index exists. 134 */ 135 public static int indexOf(double[] array, double target) { 136 return indexOf(array, target, 0, array.length); 137 } 138 139 // TODO(kevinb): consider making this public 140 private static int indexOf(double[] array, double target, int start, int end) { 141 for (int i = start; i < end; i++) { 142 if (array[i] == target) { 143 return i; 144 } 145 } 146 return -1; 147 } 148 149 /** 150 * Returns the start position of the first occurrence of the specified {@code target} within 151 * {@code array}, or {@code -1} if there is no such occurrence. 152 * 153 * <p>More formally, returns the lowest index {@code i} such that {@code Arrays.copyOfRange(array, 154 * i, i + target.length)} contains exactly the same elements as {@code target}. 155 * 156 * <p>Note that this always returns {@code -1} when {@code target} contains {@code NaN}. 157 * 158 * @param array the array to search for the sequence {@code target} 159 * @param target the array to search for as a sub-sequence of {@code array} 160 */ 161 public static int indexOf(double[] array, double[] target) { 162 checkNotNull(array, "array"); 163 checkNotNull(target, "target"); 164 if (target.length == 0) { 165 return 0; 166 } 167 168 outer: 169 for (int i = 0; i < array.length - target.length + 1; i++) { 170 for (int j = 0; j < target.length; j++) { 171 if (array[i + j] != target[j]) { 172 continue outer; 173 } 174 } 175 return i; 176 } 177 return -1; 178 } 179 180 /** 181 * Returns the index of the last appearance of the value {@code target} in {@code array}. Note 182 * that this always returns {@code -1} when {@code target} is {@code NaN}. 183 * 184 * @param array an array of {@code double} values, possibly empty 185 * @param target a primitive {@code double} value 186 * @return the greatest index {@code i} for which {@code array[i] == target}, or {@code -1} if no 187 * such index exists. 188 */ 189 public static int lastIndexOf(double[] array, double target) { 190 return lastIndexOf(array, target, 0, array.length); 191 } 192 193 // TODO(kevinb): consider making this public 194 private static int lastIndexOf(double[] array, double target, int start, int end) { 195 for (int i = end - 1; i >= start; i--) { 196 if (array[i] == target) { 197 return i; 198 } 199 } 200 return -1; 201 } 202 203 /** 204 * Returns the least value present in {@code array}, using the same rules of comparison as {@link 205 * Math#min(double, double)}. 206 * 207 * @param array a <i>nonempty</i> array of {@code double} values 208 * @return the value present in {@code array} that is less than or equal to every other value in 209 * the array 210 * @throws IllegalArgumentException if {@code array} is empty 211 */ 212 @GwtIncompatible( 213 "Available in GWT! Annotation is to avoid conflict with GWT specialization of base class.") 214 public static double min(double... array) { 215 checkArgument(array.length > 0); 216 double min = array[0]; 217 for (int i = 1; i < array.length; i++) { 218 min = Math.min(min, array[i]); 219 } 220 return min; 221 } 222 223 /** 224 * Returns the greatest value present in {@code array}, using the same rules of comparison as 225 * {@link Math#max(double, double)}. 226 * 227 * @param array a <i>nonempty</i> array of {@code double} values 228 * @return the value present in {@code array} that is greater than or equal to every other value 229 * in the array 230 * @throws IllegalArgumentException if {@code array} is empty 231 */ 232 @GwtIncompatible( 233 "Available in GWT! Annotation is to avoid conflict with GWT specialization of base class.") 234 public static double max(double... array) { 235 checkArgument(array.length > 0); 236 double max = array[0]; 237 for (int i = 1; i < array.length; i++) { 238 max = Math.max(max, array[i]); 239 } 240 return max; 241 } 242 243 /** 244 * Returns the value nearest to {@code value} which is within the closed range {@code [min..max]}. 245 * 246 * <p>If {@code value} is within the range {@code [min..max]}, {@code value} is returned 247 * unchanged. If {@code value} is less than {@code min}, {@code min} is returned, and if {@code 248 * value} is greater than {@code max}, {@code max} is returned. 249 * 250 * <p><b>Java 21+ users:</b> Use {@link Math#clamp(double, double, double)} instead. 251 * 252 * @param value the {@code double} value to constrain 253 * @param min the lower bound (inclusive) of the range to constrain {@code value} to 254 * @param max the upper bound (inclusive) of the range to constrain {@code value} to 255 * @throws IllegalArgumentException if {@code min > max} 256 * @since 21.0 257 */ 258 public static double constrainToRange(double value, double min, double max) { 259 // avoid auto-boxing by not using Preconditions.checkArgument(); see Guava issue 3984 260 // Reject NaN by testing for the good case (min <= max) instead of the bad (min > max). 261 if (min <= max) { 262 return Math.min(Math.max(value, min), max); 263 } 264 throw new IllegalArgumentException( 265 lenientFormat("min (%s) must be less than or equal to max (%s)", min, max)); 266 } 267 268 /** 269 * Returns the values from each provided array combined into a single array. For example, {@code 270 * concat(new double[] {a, b}, new double[] {}, new double[] {c}} returns the array {@code {a, b, 271 * c}}. 272 * 273 * @param arrays zero or more {@code double} arrays 274 * @return a single array containing all the values from the source arrays, in order 275 * @throws IllegalArgumentException if the total number of elements in {@code arrays} does not fit 276 * in an {@code int} 277 */ 278 public static double[] concat(double[]... arrays) { 279 long length = 0; 280 for (double[] array : arrays) { 281 length += array.length; 282 } 283 double[] result = new double[checkNoOverflow(length)]; 284 int pos = 0; 285 for (double[] array : arrays) { 286 arraycopy(array, 0, result, pos, array.length); 287 pos += array.length; 288 } 289 return result; 290 } 291 292 private static int checkNoOverflow(long result) { 293 checkArgument( 294 result == (int) result, 295 "the total number of elements (%s) in the arrays must fit in an int", 296 result); 297 return (int) result; 298 } 299 300 private static final class DoubleConverter extends Converter<String, Double> 301 implements Serializable { 302 static final Converter<String, Double> INSTANCE = new DoubleConverter(); 303 304 @Override 305 protected Double doForward(String value) { 306 return Double.valueOf(value); 307 } 308 309 @Override 310 protected String doBackward(Double value) { 311 return value.toString(); 312 } 313 314 @Override 315 public String toString() { 316 return "Doubles.stringConverter()"; 317 } 318 319 private Object readResolve() { 320 return INSTANCE; 321 } 322 323 @GwtIncompatible @J2ktIncompatible private static final long serialVersionUID = 1; 324 } 325 326 /** 327 * Returns a serializable converter object that converts between strings and doubles using {@link 328 * Double#valueOf} and {@link Double#toString()}. 329 * 330 * @since 16.0 331 */ 332 public static Converter<String, Double> stringConverter() { 333 return DoubleConverter.INSTANCE; 334 } 335 336 /** 337 * Returns an array containing the same values as {@code array}, but guaranteed to be of a 338 * specified minimum length. If {@code array} already has a length of at least {@code minLength}, 339 * it is returned directly. Otherwise, a new array of size {@code minLength + padding} is 340 * returned, containing the values of {@code array}, and zeroes in the remaining places. 341 * 342 * @param array the source array 343 * @param minLength the minimum length the returned array must guarantee 344 * @param padding an extra amount to "grow" the array by if growth is necessary 345 * @throws IllegalArgumentException if {@code minLength} or {@code padding} is negative 346 * @return an array containing the values of {@code array}, with guaranteed minimum length {@code 347 * minLength} 348 */ 349 public static double[] ensureCapacity(double[] array, int minLength, int padding) { 350 checkArgument(minLength >= 0, "Invalid minLength: %s", minLength); 351 checkArgument(padding >= 0, "Invalid padding: %s", padding); 352 return (array.length < minLength) ? Arrays.copyOf(array, minLength + padding) : array; 353 } 354 355 /** 356 * Returns a string containing the supplied {@code double} values, converted to strings as 357 * specified by {@link Double#toString(double)}, and separated by {@code separator}. For example, 358 * {@code join("-", 1.0, 2.0, 3.0)} returns the string {@code "1.0-2.0-3.0"}. 359 * 360 * <p>Note that {@link Double#toString(double)} formats {@code double} differently in GWT 361 * sometimes. In the previous example, it returns the string {@code "1-2-3"}. 362 * 363 * @param separator the text that should appear between consecutive values in the resulting string 364 * (but not at the start or end) 365 * @param array an array of {@code double} values, possibly empty 366 */ 367 public static String join(String separator, double... array) { 368 checkNotNull(separator); 369 if (array.length == 0) { 370 return ""; 371 } 372 373 // For pre-sizing a builder, just get the right order of magnitude 374 StringBuilder builder = new StringBuilder(array.length * 12); 375 builder.append(array[0]); 376 for (int i = 1; i < array.length; i++) { 377 builder.append(separator).append(array[i]); 378 } 379 return builder.toString(); 380 } 381 382 /** 383 * Returns a comparator that compares two {@code double} arrays <a 384 * href="http://en.wikipedia.org/wiki/Lexicographical_order">lexicographically</a>. That is, it 385 * compares, using {@link #compare(double, double)}), the first pair of values that follow any 386 * common prefix, or when one array is a prefix of the other, treats the shorter array as the 387 * lesser. For example, {@code [] < [1.0] < [1.0, 2.0] < [2.0]}. 388 * 389 * <p>The returned comparator is inconsistent with {@link Object#equals(Object)} (since arrays 390 * support only identity equality), but it is consistent with {@link Arrays#equals(double[], 391 * double[])}. 392 * 393 * @since 2.0 394 */ 395 public static Comparator<double[]> lexicographicalComparator() { 396 return LexicographicalComparator.INSTANCE; 397 } 398 399 private enum LexicographicalComparator implements Comparator<double[]> { 400 INSTANCE; 401 402 @Override 403 public int compare(double[] left, double[] right) { 404 int minLength = Math.min(left.length, right.length); 405 for (int i = 0; i < minLength; i++) { 406 int result = Double.compare(left[i], right[i]); 407 if (result != 0) { 408 return result; 409 } 410 } 411 return left.length - right.length; 412 } 413 414 @Override 415 public String toString() { 416 return "Doubles.lexicographicalComparator()"; 417 } 418 } 419 420 /** 421 * Sorts the elements of {@code array} in descending order. 422 * 423 * <p>Note that this method uses the total order imposed by {@link Double#compare}, which treats 424 * all NaN values as equal and 0.0 as greater than -0.0. 425 * 426 * @since 23.1 427 */ 428 public static void sortDescending(double[] array) { 429 checkNotNull(array); 430 sortDescending(array, 0, array.length); 431 } 432 433 /** 434 * Sorts the elements of {@code array} between {@code fromIndex} inclusive and {@code toIndex} 435 * exclusive in descending order. 436 * 437 * <p>Note that this method uses the total order imposed by {@link Double#compare}, which treats 438 * all NaN values as equal and 0.0 as greater than -0.0. 439 * 440 * @since 23.1 441 */ 442 public static void sortDescending(double[] array, int fromIndex, int toIndex) { 443 checkNotNull(array); 444 checkPositionIndexes(fromIndex, toIndex, array.length); 445 sort(array, fromIndex, toIndex); 446 reverse(array, fromIndex, toIndex); 447 } 448 449 /** 450 * Reverses the elements of {@code array}. This is equivalent to {@code 451 * Collections.reverse(Doubles.asList(array))}, but is likely to be more efficient. 452 * 453 * @since 23.1 454 */ 455 public static void reverse(double[] array) { 456 checkNotNull(array); 457 reverse(array, 0, array.length); 458 } 459 460 /** 461 * Reverses the elements of {@code array} between {@code fromIndex} inclusive and {@code toIndex} 462 * exclusive. This is equivalent to {@code 463 * Collections.reverse(Doubles.asList(array).subList(fromIndex, toIndex))}, but is likely to be 464 * more efficient. 465 * 466 * @throws IndexOutOfBoundsException if {@code fromIndex < 0}, {@code toIndex > array.length}, or 467 * {@code toIndex > fromIndex} 468 * @since 23.1 469 */ 470 public static void reverse(double[] array, int fromIndex, int toIndex) { 471 checkNotNull(array); 472 checkPositionIndexes(fromIndex, toIndex, array.length); 473 for (int i = fromIndex, j = toIndex - 1; i < j; i++, j--) { 474 double tmp = array[i]; 475 array[i] = array[j]; 476 array[j] = tmp; 477 } 478 } 479 480 /** 481 * Performs a right rotation of {@code array} of "distance" places, so that the first element is 482 * moved to index "distance", and the element at index {@code i} ends up at index {@code (distance 483 * + i) mod array.length}. This is equivalent to {@code Collections.rotate(Bytes.asList(array), 484 * distance)}, but is considerably faster and avoids allocation and garbage collection. 485 * 486 * <p>The provided "distance" may be negative, which will rotate left. 487 * 488 * @since 32.0.0 489 */ 490 public static void rotate(double[] array, int distance) { 491 rotate(array, distance, 0, array.length); 492 } 493 494 /** 495 * Performs a right rotation of {@code array} between {@code fromIndex} inclusive and {@code 496 * toIndex} exclusive. This is equivalent to {@code 497 * Collections.rotate(Bytes.asList(array).subList(fromIndex, toIndex), distance)}, but is 498 * considerably faster and avoids allocations and garbage collection. 499 * 500 * <p>The provided "distance" may be negative, which will rotate left. 501 * 502 * @throws IndexOutOfBoundsException if {@code fromIndex < 0}, {@code toIndex > array.length}, or 503 * {@code toIndex > fromIndex} 504 * @since 32.0.0 505 */ 506 public static void rotate(double[] array, int distance, int fromIndex, int toIndex) { 507 // See Ints.rotate for more details about possible algorithms here. 508 checkNotNull(array); 509 checkPositionIndexes(fromIndex, toIndex, array.length); 510 if (array.length <= 1) { 511 return; 512 } 513 514 int length = toIndex - fromIndex; 515 // Obtain m = (-distance mod length), a non-negative value less than "length". This is how many 516 // places left to rotate. 517 int m = -distance % length; 518 m = (m < 0) ? m + length : m; 519 // The current index of what will become the first element of the rotated section. 520 int newFirstIndex = m + fromIndex; 521 if (newFirstIndex == fromIndex) { 522 return; 523 } 524 525 reverse(array, fromIndex, newFirstIndex); 526 reverse(array, newFirstIndex, toIndex); 527 reverse(array, fromIndex, toIndex); 528 } 529 530 /** 531 * Returns an array containing each value of {@code collection}, converted to a {@code double} 532 * value in the manner of {@link Number#doubleValue}. 533 * 534 * <p>Elements are copied from the argument collection as if by {@code collection.toArray()}. 535 * Calling this method is as thread-safe as calling that method. 536 * 537 * @param collection a collection of {@code Number} instances 538 * @return an array containing the same values as {@code collection}, in the same order, converted 539 * to primitives 540 * @throws NullPointerException if {@code collection} or any of its elements is null 541 * @since 1.0 (parameter was {@code Collection<Double>} before 12.0) 542 */ 543 public static double[] toArray(Collection<? extends Number> collection) { 544 if (collection instanceof DoubleArrayAsList) { 545 return ((DoubleArrayAsList) collection).toDoubleArray(); 546 } 547 548 Object[] boxedArray = collection.toArray(); 549 int len = boxedArray.length; 550 double[] array = new double[len]; 551 for (int i = 0; i < len; i++) { 552 // checkNotNull for GWT (do not optimize) 553 array[i] = ((Number) checkNotNull(boxedArray[i])).doubleValue(); 554 } 555 return array; 556 } 557 558 /** 559 * Returns a fixed-size list backed by the specified array, similar to {@link 560 * Arrays#asList(Object[])}. The list supports {@link List#set(int, Object)}, but any attempt to 561 * set a value to {@code null} will result in a {@link NullPointerException}. 562 * 563 * <p>The returned list maintains the values, but not the identities, of {@code Double} objects 564 * written to or read from it. For example, whether {@code list.get(0) == list.get(0)} is true for 565 * the returned list is unspecified. 566 * 567 * <p>The returned list may have unexpected behavior if it contains {@code NaN}, or if {@code NaN} 568 * is used as a parameter to any of its methods. 569 * 570 * <p>The returned list is serializable. 571 * 572 * <p><b>Note:</b> when possible, you should represent your data as an {@link 573 * ImmutableDoubleArray} instead, which has an {@link ImmutableDoubleArray#asList asList} view. 574 * 575 * @param backingArray the array to back the list 576 * @return a list view of the array 577 */ 578 public static List<Double> asList(double... backingArray) { 579 if (backingArray.length == 0) { 580 return emptyList(); 581 } 582 return new DoubleArrayAsList(backingArray); 583 } 584 585 private static final class DoubleArrayAsList extends AbstractList<Double> 586 implements RandomAccess, Serializable { 587 final double[] array; 588 final int start; 589 final int end; 590 591 DoubleArrayAsList(double[] array) { 592 this(array, 0, array.length); 593 } 594 595 DoubleArrayAsList(double[] array, int start, int end) { 596 this.array = array; 597 this.start = start; 598 this.end = end; 599 } 600 601 @Override 602 public int size() { 603 return end - start; 604 } 605 606 @Override 607 public boolean isEmpty() { 608 return false; 609 } 610 611 @Override 612 public Double get(int index) { 613 checkElementIndex(index, size()); 614 return array[start + index]; 615 } 616 617 @Override 618 public Spliterator.OfDouble spliterator() { 619 return Spliterators.spliterator(array, start, end, 0); 620 } 621 622 @Override 623 public boolean contains(@Nullable Object target) { 624 // Overridden to prevent a ton of boxing 625 return (target instanceof Double) 626 && Doubles.indexOf(array, (Double) target, start, end) != -1; 627 } 628 629 @Override 630 public int indexOf(@Nullable Object target) { 631 // Overridden to prevent a ton of boxing 632 if (target instanceof Double) { 633 int i = Doubles.indexOf(array, (Double) target, start, end); 634 if (i >= 0) { 635 return i - start; 636 } 637 } 638 return -1; 639 } 640 641 @Override 642 public int lastIndexOf(@Nullable Object target) { 643 // Overridden to prevent a ton of boxing 644 if (target instanceof Double) { 645 int i = Doubles.lastIndexOf(array, (Double) target, start, end); 646 if (i >= 0) { 647 return i - start; 648 } 649 } 650 return -1; 651 } 652 653 @Override 654 public Double set(int index, Double element) { 655 checkElementIndex(index, size()); 656 double oldValue = array[start + index]; 657 // checkNotNull for GWT (do not optimize) 658 array[start + index] = checkNotNull(element); 659 return oldValue; 660 } 661 662 @Override 663 public List<Double> subList(int fromIndex, int toIndex) { 664 int size = size(); 665 checkPositionIndexes(fromIndex, toIndex, size); 666 if (fromIndex == toIndex) { 667 return emptyList(); 668 } 669 return new DoubleArrayAsList(array, start + fromIndex, start + toIndex); 670 } 671 672 @Override 673 public boolean equals(@Nullable Object object) { 674 if (object == this) { 675 return true; 676 } 677 if (object instanceof DoubleArrayAsList) { 678 DoubleArrayAsList that = (DoubleArrayAsList) object; 679 int size = size(); 680 if (that.size() != size) { 681 return false; 682 } 683 for (int i = 0; i < size; i++) { 684 if (array[start + i] != that.array[that.start + i]) { 685 return false; 686 } 687 } 688 return true; 689 } 690 return super.equals(object); 691 } 692 693 @Override 694 public int hashCode() { 695 int result = 1; 696 for (int i = start; i < end; i++) { 697 result = 31 * result + Double.hashCode(array[i]); 698 } 699 return result; 700 } 701 702 @Override 703 public String toString() { 704 StringBuilder builder = new StringBuilder(size() * 12); 705 builder.append('[').append(array[start]); 706 for (int i = start + 1; i < end; i++) { 707 builder.append(", ").append(array[i]); 708 } 709 return builder.append(']').toString(); 710 } 711 712 double[] toDoubleArray() { 713 return Arrays.copyOfRange(array, start, end); 714 } 715 716 @GwtIncompatible @J2ktIncompatible private static final long serialVersionUID = 0; 717 } 718 719 /** 720 * This is adapted from the regex suggested by {@link Double#valueOf(String)} for prevalidating 721 * inputs. All valid inputs must pass this regex, but it's semantically fine if not all inputs 722 * that pass this regex are valid -- only a performance hit is incurred, not a semantics bug. 723 */ 724 @GwtIncompatible // regular expressions 725 static final 726 java.util.regex.Pattern 727 FLOATING_POINT_PATTERN = fpPattern(); 728 729 @GwtIncompatible // regular expressions 730 private static 731 java.util.regex.Pattern 732 fpPattern() { 733 /* 734 * We use # instead of * for possessive quantifiers. This lets us strip them out when building 735 * the regex for RE2 (which doesn't support them) but leave them in when building it for 736 * java.util.regex (where we want them in order to avoid catastrophic backtracking). 737 */ 738 String decimal = "(?:\\d+#(?:\\.\\d*#)?|\\.\\d+#)"; 739 String completeDec = decimal + "(?:[eE][+-]?\\d+#)?[fFdD]?"; 740 String hex = "(?:[0-9a-fA-F]+#(?:\\.[0-9a-fA-F]*#)?|\\.[0-9a-fA-F]+#)"; 741 String completeHex = "0[xX]" + hex + "[pP][+-]?\\d+#[fFdD]?"; 742 String fpPattern = "[+-]?(?:NaN|Infinity|" + completeDec + "|" + completeHex + ")"; 743 fpPattern = 744 fpPattern.replace( 745 "#", 746 "+" 747 ); 748 return 749 java.util.regex.Pattern 750 .compile(fpPattern); 751 } 752 753 /** 754 * Parses the specified string as a double-precision floating point value. The ASCII character 755 * {@code '-'} (U+002D) is recognized as the minus sign. 756 * 757 * <p>Unlike {@link Double#parseDouble(String)}, this method returns {@code null} instead of 758 * throwing an exception if parsing fails. Valid inputs are exactly those accepted by {@link 759 * Double#valueOf(String)}, except that leading and trailing whitespace is not permitted. 760 * 761 * <p>This implementation is likely to be faster than {@code Double.parseDouble} if many failures 762 * are expected. 763 * 764 * @param string the string representation of a {@code double} value 765 * @return the floating point value represented by {@code string}, or {@code null} if {@code 766 * string} has a length of zero or cannot be parsed as a {@code double} value 767 * @throws NullPointerException if {@code string} is {@code null} 768 * @since 14.0 769 */ 770 @GwtIncompatible // regular expressions 771 public static @Nullable Double tryParse(String string) { 772 if (FLOATING_POINT_PATTERN.matcher(string).matches()) { 773 // TODO(lowasser): could be potentially optimized, but only with 774 // extensive testing 775 try { 776 return parseDouble(string); 777 } catch (NumberFormatException e) { 778 // Double.parseDouble has changed specs several times, so fall through 779 // gracefully 780 } 781 } 782 return null; 783 } 784}