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