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