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