Home | History | Annotate | Download | only in primitives
      1 /*
      2  * Copyright (C) 2008 The Guava Authors
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License");
      5  * you may not use this file except in compliance with the License.
      6  * You may obtain a copy of the License at
      7  *
      8  * http://www.apache.org/licenses/LICENSE-2.0
      9  *
     10  * Unless required by applicable law or agreed to in writing, software
     11  * distributed under the License is distributed on an "AS IS" BASIS,
     12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13  * See the License for the specific language governing permissions and
     14  * limitations under the License.
     15  */
     16 
     17 package com.google.common.primitives;
     18 
     19 import static com.google.common.base.Preconditions.checkArgument;
     20 import static com.google.common.base.Preconditions.checkElementIndex;
     21 import static com.google.common.base.Preconditions.checkNotNull;
     22 import static com.google.common.base.Preconditions.checkPositionIndexes;
     23 import static java.lang.Double.NEGATIVE_INFINITY;
     24 import static java.lang.Double.POSITIVE_INFINITY;
     25 
     26 import com.google.common.annotations.GwtCompatible;
     27 
     28 import java.io.Serializable;
     29 import java.util.AbstractList;
     30 import java.util.Arrays;
     31 import java.util.Collection;
     32 import java.util.Collections;
     33 import java.util.Comparator;
     34 import java.util.List;
     35 import java.util.RandomAccess;
     36 
     37 /**
     38  * Static utility methods pertaining to {@code double} primitives, that are not
     39  * already found in either {@link Double} or {@link Arrays}.
     40  *
     41  * @author Kevin Bourrillion
     42  * @since 1.0
     43  */
     44 @GwtCompatible
     45 public final class Doubles {
     46   private Doubles() {}
     47 
     48   /**
     49    * The number of bytes required to represent a primitive {@code double}
     50    * value.
     51    *
     52    * @since 10.0
     53    */
     54   public static final int BYTES = Double.SIZE / Byte.SIZE;
     55 
     56   /**
     57    * Returns a hash code for {@code value}; equal to the result of invoking
     58    * {@code ((Double) value).hashCode()}.
     59    *
     60    * @param value a primitive {@code double} value
     61    * @return a hash code for the value
     62    */
     63   public static int hashCode(double value) {
     64     return ((Double) value).hashCode();
     65     // TODO(kevinb): do it this way when we can (GWT problem):
     66     // long bits = Double.doubleToLongBits(value);
     67     // return (int)(bits ^ (bits >>> 32));
     68   }
     69 
     70   /**
     71    * Compares the two specified {@code double} values. The sign of the value
     72    * returned is the same as that of <code>((Double) a).{@linkplain
     73    * Double#compareTo compareTo}(b)</code>. As with that method, {@code NaN} is
     74    * treated as greater than all other values, and {@code 0.0 > -0.0}.
     75    *
     76    * @param a the first {@code double} to compare
     77    * @param b the second {@code double} to compare
     78    * @return a negative value if {@code a} is less than {@code b}; a positive
     79    *     value if {@code a} is greater than {@code b}; or zero if they are equal
     80    */
     81   public static int compare(double a, double b) {
     82     return Double.compare(a, b);
     83   }
     84 
     85   /**
     86    * Returns {@code true} if {@code value} represents a real number. This is
     87    * equivalent to, but not necessarily implemented as,
     88    * {@code !(Double.isInfinite(value) || Double.isNaN(value))}.
     89    *
     90    * @since 10.0
     91    */
     92   public static boolean isFinite(double value) {
     93     return NEGATIVE_INFINITY < value & value < POSITIVE_INFINITY;
     94   }
     95 
     96   /**
     97    * Returns {@code true} if {@code target} is present as an element anywhere in
     98    * {@code array}. Note that this always returns {@code false} when {@code
     99    * target} is {@code NaN}.
    100    *
    101    * @param array an array of {@code double} values, possibly empty
    102    * @param target a primitive {@code double} value
    103    * @return {@code true} if {@code array[i] == target} for some value of {@code
    104    *     i}
    105    */
    106   public static boolean contains(double[] array, double target) {
    107     for (double value : array) {
    108       if (value == target) {
    109         return true;
    110       }
    111     }
    112     return false;
    113   }
    114 
    115   /**
    116    * Returns the index of the first appearance of the value {@code target} in
    117    * {@code array}. Note that this always returns {@code -1} when {@code target}
    118    * is {@code NaN}.
    119    *
    120    * @param array an array of {@code double} values, possibly empty
    121    * @param target a primitive {@code double} value
    122    * @return the least index {@code i} for which {@code array[i] == target}, or
    123    *     {@code -1} if no such index exists.
    124    */
    125   public static int indexOf(double[] array, double target) {
    126     return indexOf(array, target, 0, array.length);
    127   }
    128 
    129   // TODO(kevinb): consider making this public
    130   private static int indexOf(
    131       double[] array, double target, int start, int end) {
    132     for (int i = start; i < end; i++) {
    133       if (array[i] == target) {
    134         return i;
    135       }
    136     }
    137     return -1;
    138   }
    139 
    140   /**
    141    * Returns the start position of the first occurrence of the specified {@code
    142    * target} within {@code array}, or {@code -1} if there is no such occurrence.
    143    *
    144    * <p>More formally, returns the lowest index {@code i} such that {@code
    145    * java.util.Arrays.copyOfRange(array, i, i + target.length)} contains exactly
    146    * the same elements as {@code target}.
    147    *
    148    * <p>Note that this always returns {@code -1} when {@code target} contains
    149    * {@code NaN}.
    150    *
    151    * @param array the array to search for the sequence {@code target}
    152    * @param target the array to search for as a sub-sequence of {@code array}
    153    */
    154   public static int indexOf(double[] array, double[] target) {
    155     checkNotNull(array, "array");
    156     checkNotNull(target, "target");
    157     if (target.length == 0) {
    158       return 0;
    159     }
    160 
    161     outer:
    162     for (int i = 0; i < array.length - target.length + 1; i++) {
    163       for (int j = 0; j < target.length; j++) {
    164         if (array[i + j] != target[j]) {
    165           continue outer;
    166         }
    167       }
    168       return i;
    169     }
    170     return -1;
    171   }
    172 
    173   /**
    174    * Returns the index of the last appearance of the value {@code target} in
    175    * {@code array}. Note that this always returns {@code -1} when {@code target}
    176    * is {@code NaN}.
    177    *
    178    * @param array an array of {@code double} values, possibly empty
    179    * @param target a primitive {@code double} value
    180    * @return the greatest index {@code i} for which {@code array[i] == target},
    181    *     or {@code -1} if no such index exists.
    182    */
    183   public static int lastIndexOf(double[] array, double target) {
    184     return lastIndexOf(array, target, 0, array.length);
    185   }
    186 
    187   // TODO(kevinb): consider making this public
    188   private static int lastIndexOf(
    189       double[] array, double target, int start, int end) {
    190     for (int i = end - 1; i >= start; i--) {
    191       if (array[i] == target) {
    192         return i;
    193       }
    194     }
    195     return -1;
    196   }
    197 
    198   /**
    199    * Returns the least value present in {@code array}, using the same rules of
    200    * comparison as {@link Math#min(double, double)}.
    201    *
    202    * @param array a <i>nonempty</i> array of {@code double} values
    203    * @return the value present in {@code array} that is less than or equal to
    204    *     every other value in the array
    205    * @throws IllegalArgumentException if {@code array} is empty
    206    */
    207   public static double min(double... array) {
    208     checkArgument(array.length > 0);
    209     double min = array[0];
    210     for (int i = 1; i < array.length; i++) {
    211       min = Math.min(min, array[i]);
    212     }
    213     return min;
    214   }
    215 
    216   /**
    217    * Returns the greatest value present in {@code array}, using the same rules
    218    * of comparison as {@link Math#max(double, double)}.
    219    *
    220    * @param array a <i>nonempty</i> array of {@code double} values
    221    * @return the value present in {@code array} that is greater than or equal to
    222    *     every other value in the array
    223    * @throws IllegalArgumentException if {@code array} is empty
    224    */
    225   public static double max(double... array) {
    226     checkArgument(array.length > 0);
    227     double max = array[0];
    228     for (int i = 1; i < array.length; i++) {
    229       max = Math.max(max, array[i]);
    230     }
    231     return max;
    232   }
    233 
    234   /**
    235    * Returns the values from each provided array combined into a single array.
    236    * For example, {@code concat(new double[] {a, b}, new double[] {}, new
    237    * double[] {c}} returns the array {@code {a, b, c}}.
    238    *
    239    * @param arrays zero or more {@code double} arrays
    240    * @return a single array containing all the values from the source arrays, in
    241    *     order
    242    */
    243   public static double[] concat(double[]... arrays) {
    244     int length = 0;
    245     for (double[] array : arrays) {
    246       length += array.length;
    247     }
    248     double[] result = new double[length];
    249     int pos = 0;
    250     for (double[] array : arrays) {
    251       System.arraycopy(array, 0, result, pos, array.length);
    252       pos += array.length;
    253     }
    254     return result;
    255   }
    256 
    257   /**
    258    * Returns an array containing the same values as {@code array}, but
    259    * guaranteed to be of a specified minimum length. If {@code array} already
    260    * has a length of at least {@code minLength}, it is returned directly.
    261    * Otherwise, a new array of size {@code minLength + padding} is returned,
    262    * containing the values of {@code array}, and zeroes in the remaining places.
    263    *
    264    * @param array the source array
    265    * @param minLength the minimum length the returned array must guarantee
    266    * @param padding an extra amount to "grow" the array by if growth is
    267    *     necessary
    268    * @throws IllegalArgumentException if {@code minLength} or {@code padding} is
    269    *     negative
    270    * @return an array containing the values of {@code array}, with guaranteed
    271    *     minimum length {@code minLength}
    272    */
    273   public static double[] ensureCapacity(
    274       double[] array, int minLength, int padding) {
    275     checkArgument(minLength >= 0, "Invalid minLength: %s", minLength);
    276     checkArgument(padding >= 0, "Invalid padding: %s", padding);
    277     return (array.length < minLength)
    278         ? copyOf(array, minLength + padding)
    279         : array;
    280   }
    281 
    282   // Arrays.copyOf() requires Java 6
    283   private static double[] copyOf(double[] original, int length) {
    284     double[] copy = new double[length];
    285     System.arraycopy(original, 0, copy, 0, Math.min(original.length, length));
    286     return copy;
    287   }
    288 
    289   /**
    290    * Returns a string containing the supplied {@code double} values, converted
    291    * to strings as specified by {@link Double#toString(double)}, and separated
    292    * by {@code separator}. For example, {@code join("-", 1.0, 2.0, 3.0)} returns
    293    * the string {@code "1.0-2.0-3.0"}.
    294    *
    295    * <p>Note that {@link Double#toString(double)} formats {@code double}
    296    * differently in GWT sometimes.  In the previous example, it returns the string
    297    * {@code "1-2-3"}.
    298    *
    299    * @param separator the text that should appear between consecutive values in
    300    *     the resulting string (but not at the start or end)
    301    * @param array an array of {@code double} values, possibly empty
    302    */
    303   public static String join(String separator, double... array) {
    304     checkNotNull(separator);
    305     if (array.length == 0) {
    306       return "";
    307     }
    308 
    309     // For pre-sizing a builder, just get the right order of magnitude
    310     StringBuilder builder = new StringBuilder(array.length * 12);
    311     builder.append(array[0]);
    312     for (int i = 1; i < array.length; i++) {
    313       builder.append(separator).append(array[i]);
    314     }
    315     return builder.toString();
    316   }
    317 
    318   /**
    319    * Returns a comparator that compares two {@code double} arrays
    320    * lexicographically. That is, it compares, using {@link
    321    * #compare(double, double)}), the first pair of values that follow any
    322    * common prefix, or when one array is a prefix of the other, treats the
    323    * shorter array as the lesser. For example,
    324    * {@code [] < [1.0] < [1.0, 2.0] < [2.0]}.
    325    *
    326    * <p>The returned comparator is inconsistent with {@link
    327    * Object#equals(Object)} (since arrays support only identity equality), but
    328    * it is consistent with {@link Arrays#equals(double[], double[])}.
    329    *
    330    * @see <a href="http://en.wikipedia.org/wiki/Lexicographical_order">
    331    *     Lexicographical order article at Wikipedia</a>
    332    * @since 2.0
    333    */
    334   public static Comparator<double[]> lexicographicalComparator() {
    335     return LexicographicalComparator.INSTANCE;
    336   }
    337 
    338   private enum LexicographicalComparator implements Comparator<double[]> {
    339     INSTANCE;
    340 
    341     @Override
    342     public int compare(double[] left, double[] right) {
    343       int minLength = Math.min(left.length, right.length);
    344       for (int i = 0; i < minLength; i++) {
    345         int result = Doubles.compare(left[i], right[i]);
    346         if (result != 0) {
    347           return result;
    348         }
    349       }
    350       return left.length - right.length;
    351     }
    352   }
    353 
    354   /**
    355    * Copies a collection of {@code Double} instances into a new array of
    356    * primitive {@code double} values.
    357    *
    358    * <p>Elements are copied from the argument collection as if by {@code
    359    * collection.toArray()}.  Calling this method is as thread-safe as calling
    360    * that method.
    361    *
    362    * @param collection a collection of {@code Double} objects
    363    * @return an array containing the same values as {@code collection}, in the
    364    *     same order, converted to primitives
    365    * @throws NullPointerException if {@code collection} or any of its elements
    366    *     is null
    367    */
    368   public static double[] toArray(Collection<Double> collection) {
    369     if (collection instanceof DoubleArrayAsList) {
    370       return ((DoubleArrayAsList) collection).toDoubleArray();
    371     }
    372 
    373     Object[] boxedArray = collection.toArray();
    374     int len = boxedArray.length;
    375     double[] array = new double[len];
    376     for (int i = 0; i < len; i++) {
    377       // checkNotNull for GWT (do not optimize)
    378       array[i] = (Double) checkNotNull(boxedArray[i]);
    379     }
    380     return array;
    381   }
    382 
    383   /**
    384    * Returns a fixed-size list backed by the specified array, similar to {@link
    385    * Arrays#asList(Object[])}. The list supports {@link List#set(int, Object)},
    386    * but any attempt to set a value to {@code null} will result in a {@link
    387    * NullPointerException}.
    388    *
    389    * <p>The returned list maintains the values, but not the identities, of
    390    * {@code Double} objects written to or read from it.  For example, whether
    391    * {@code list.get(0) == list.get(0)} is true for the returned list is
    392    * unspecified.
    393    *
    394    * <p>The returned list may have unexpected behavior if it contains {@code
    395    * NaN}, or if {@code NaN} is used as a parameter to any of its methods.
    396    *
    397    * @param backingArray the array to back the list
    398    * @return a list view of the array
    399    */
    400   public static List<Double> asList(double... backingArray) {
    401     if (backingArray.length == 0) {
    402       return Collections.emptyList();
    403     }
    404     return new DoubleArrayAsList(backingArray);
    405   }
    406 
    407   @GwtCompatible
    408   private static class DoubleArrayAsList extends AbstractList<Double>
    409       implements RandomAccess, Serializable {
    410     final double[] array;
    411     final int start;
    412     final int end;
    413 
    414     DoubleArrayAsList(double[] array) {
    415       this(array, 0, array.length);
    416     }
    417 
    418     DoubleArrayAsList(double[] array, int start, int end) {
    419       this.array = array;
    420       this.start = start;
    421       this.end = end;
    422     }
    423 
    424     @Override public int size() {
    425       return end - start;
    426     }
    427 
    428     @Override public boolean isEmpty() {
    429       return false;
    430     }
    431 
    432     @Override public Double get(int index) {
    433       checkElementIndex(index, size());
    434       return array[start + index];
    435     }
    436 
    437     @Override public boolean contains(Object target) {
    438       // Overridden to prevent a ton of boxing
    439       return (target instanceof Double)
    440           && Doubles.indexOf(array, (Double) target, start, end) != -1;
    441     }
    442 
    443     @Override public int indexOf(Object target) {
    444       // Overridden to prevent a ton of boxing
    445       if (target instanceof Double) {
    446         int i = Doubles.indexOf(array, (Double) target, start, end);
    447         if (i >= 0) {
    448           return i - start;
    449         }
    450       }
    451       return -1;
    452     }
    453 
    454     @Override public int lastIndexOf(Object target) {
    455       // Overridden to prevent a ton of boxing
    456       if (target instanceof Double) {
    457         int i = Doubles.lastIndexOf(array, (Double) target, start, end);
    458         if (i >= 0) {
    459           return i - start;
    460         }
    461       }
    462       return -1;
    463     }
    464 
    465     @Override public Double set(int index, Double element) {
    466       checkElementIndex(index, size());
    467       double oldValue = array[start + index];
    468       array[start + index] = checkNotNull(element);  // checkNotNull for GWT (do not optimize)
    469       return oldValue;
    470     }
    471 
    472     @Override public List<Double> subList(int fromIndex, int toIndex) {
    473       int size = size();
    474       checkPositionIndexes(fromIndex, toIndex, size);
    475       if (fromIndex == toIndex) {
    476         return Collections.emptyList();
    477       }
    478       return new DoubleArrayAsList(array, start + fromIndex, start + toIndex);
    479     }
    480 
    481     @Override public boolean equals(Object object) {
    482       if (object == this) {
    483         return true;
    484       }
    485       if (object instanceof DoubleArrayAsList) {
    486         DoubleArrayAsList that = (DoubleArrayAsList) object;
    487         int size = size();
    488         if (that.size() != size) {
    489           return false;
    490         }
    491         for (int i = 0; i < size; i++) {
    492           if (array[start + i] != that.array[that.start + i]) {
    493             return false;
    494           }
    495         }
    496         return true;
    497       }
    498       return super.equals(object);
    499     }
    500 
    501     @Override public int hashCode() {
    502       int result = 1;
    503       for (int i = start; i < end; i++) {
    504         result = 31 * result + Doubles.hashCode(array[i]);
    505       }
    506       return result;
    507     }
    508 
    509     @Override public String toString() {
    510       StringBuilder builder = new StringBuilder(size() * 12);
    511       builder.append('[').append(array[start]);
    512       for (int i = start + 1; i < end; i++) {
    513         builder.append(", ").append(array[i]);
    514       }
    515       return builder.append(']').toString();
    516     }
    517 
    518     double[] toDoubleArray() {
    519       // Arrays.copyOfRange() requires Java 6
    520       int size = size();
    521       double[] result = new double[size];
    522       System.arraycopy(array, start, result, 0, size);
    523       return result;
    524     }
    525 
    526     private static final long serialVersionUID = 0;
    527   }
    528 }
    529