Class Utilities


  • public final class Utilities
    extends Object
    Miscellaneous methods, including cnvenience methods for equals and hashCode implementations. Example use case in a class called Car:
     public boolean equals(Object other) {
         if (this == aThat) {
             return true;
         }
         if (other == null || !other.getClass().equals(getClass())) {
             return false;
         }
         Car that = (Car) other;
         return Utilities.equals(this.name,              that.name)       &&
                Utilities.equals(this.numDoors,          that.numDoors)   &&
                Utilities.equals(this.gasMileage,        that.gasMileage) &&
                Utilities.equals(this.color,             that.color)      &&
                Arrays   .equals(this.maintenanceChecks, that.maintenanceChecks);
     }
     
    Note the usage of Arrays method for comparing arrays.

    This class also provides convenience methods for computing hash code values. All those methods expect a seed argument, which is the hash code value computed for previous fields in a class. For the initial seed (the one for the field for which to compute an hash code), an arbitrary value must be provided. We suggest a different number for different class in order to reduce the risk of collision between "empty" instances of different classes. Serializable classes can use (int) serialVersionUID for example.

    Since:
    2.5
    Author:
    Martin Desruisseaux (IRD)
    • Method Summary

      All Methods Static Methods Concrete Methods 
      Modifier and Type Method Description
      static void assertNotZipSlipVulnarable​(File file, Path destinationDir)
      Checks if the given filename exposes a zip slip vulnerability when it would be extracted to the given path.
      static boolean deepEquals​(Object object1, Object object2)
      Convenience method for testing two objects for equality.
      static int deepHashCode​(Object object)
      Returns a hash code for the specified object, which may be an array.
      static String deepToString​(Object object)
      Returns a string representation of the specified object, which may be an array.
      static <E> Queue<E> emptyQueue()
      Returns a queue which is always empty and accepts no element.
      static void ensureArgumentNonNull​(String name, Object object)
      Makes sure that an argument is non-null and throws an IllegalArgumentException if it is.
      static void ensureNonNull​(String name, Object object)
      Makes sure that an argument is non-null.
      static boolean equals​(boolean o1, boolean o2)
      Returns true if the given booleans are equals.
      static boolean equals​(byte o1, byte o2)
      Returns true if the given bytes are equals.
      static boolean equals​(char o1, char o2)
      Returns true if the given characters are equals.
      static boolean equals​(double o1, double o2)
      Returns true if the given doubles are equals.
      static boolean equals​(float o1, float o2)
      Returns true if the given floats are equals.
      static boolean equals​(int o1, int o2)
      Returns true if the given integers are equals.
      static boolean equals​(long o1, long o2)
      Returns true if the given longs are equals.
      static boolean equals​(short o1, short o2)
      Returns true if the given shorts are equals.
      static boolean equals​(Object object1, Object object2)
      Convenience method for testing two objects for equality.
      static int hash​(boolean value, int seed)
      Alters the given seed with the hash code value computed from the given value.
      static int hash​(char value, int seed)
      Alters the given seed with the hash code value computed from the given value.
      static int hash​(double value, int seed)
      Alters the given seed with the hash code value computed from the given value.
      static int hash​(float value, int seed)
      Alters the given seed with the hash code value computed from the given value.
      static int hash​(int value, int seed)
      Alters the given seed with the hash code value computed from the given value.
      static int hash​(long value, int seed)
      Alters the given seed with the hash code value computed from the given value.
      static int hash​(Object value, int seed)
      Alters the given seed with the hash code value computed from the given value.
      static String spaces​(int length)
      Returns a string of the specified length filled with white spaces.
      static <T> Stream<T> stream​(Iterable<T> iterable)
      Creates a stream over the specified Iterable's elements.
      static <T> Stream<T> stream​(Iterator<T> iterator)
      Creates a stream over the specified Iterator's elements.
      static <T> Stream<T> stream​(Optional<T> optional)
      Creates a stream with zero or one element, depending on whether the specified Optional is empty or not.
      static <T,​U>
      Stream<Class<? extends U>>
      streamIfSubtype​(Class<T> type, Class<U> supertype)
      Creates a stream with zero or one elements, depending on whether the specified supertype is actually a supertype of the specified type (according to supertype.isAssignableFrom(type)).
      static <T> Collector<T,​?,​Map<String,​T>> toInstanceByClassNameMap()
      Collects stream elements into a Map whose values are the stream elements and whose keys are those elements' fully qualified class names.
      static <T> Collector<T,​?,​Set<T>> toUnmodifiableSet()  
      • Methods inherited from class Object

        clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
    • Method Detail

      • equals

        public static boolean equals​(boolean o1,
                                     boolean o2)
        Returns true if the given booleans are equals. This overloaded flavor is provided only for allowing developper to invoke equals methods without consideration for the argument type.
        Parameters:
        o1 - The first value to compare.
        o2 - The second value to compare.
        Returns:
        true if both values are equal.
        See Also:
        Boolean.equals(java.lang.Object)
      • equals

        public static boolean equals​(char o1,
                                     char o2)
        Returns true if the given characters are equals. This overloaded flavor is provided only for allowing developper to invoke equals methods without consideration for the argument type.
        Parameters:
        o1 - The first value to compare.
        o2 - The second value to compare.
        Returns:
        true if both values are equal.
        See Also:
        Character.equals(java.lang.Object)
      • equals

        public static boolean equals​(byte o1,
                                     byte o2)
        Returns true if the given bytes are equals. This overloaded flavor is provided only for allowing developper to invoke equals methods without consideration for the argument type.
        Parameters:
        o1 - The first value to compare.
        o2 - The second value to compare.
        Returns:
        true if both values are equal.
        See Also:
        Byte.equals(java.lang.Object)
      • equals

        public static boolean equals​(short o1,
                                     short o2)
        Returns true if the given shorts are equals. This overloaded flavor is provided only for allowing developper to invoke equals methods without consideration for the argument type.
        Parameters:
        o1 - The first value to compare.
        o2 - The second value to compare.
        Returns:
        true if both values are equal.
        See Also:
        Short.equals(java.lang.Object)
      • equals

        public static boolean equals​(int o1,
                                     int o2)
        Returns true if the given integers are equals. This overloaded flavor is provided only for allowing developper to invoke equals methods without consideration for the argument type.
        Parameters:
        o1 - The first value to compare.
        o2 - The second value to compare.
        Returns:
        true if both values are equal.
        See Also:
        Integer.equals(java.lang.Object)
      • equals

        public static boolean equals​(long o1,
                                     long o2)
        Returns true if the given longs are equals. This overloaded flavor is provided only for allowing developper to invoke equals methods without consideration for the argument type.
        Parameters:
        o1 - The first value to compare.
        o2 - The second value to compare.
        Returns:
        true if both values are equal.
        See Also:
        Long.equals(java.lang.Object)
      • equals

        public static boolean equals​(float o1,
                                     float o2)
        Returns true if the given floats are equals. Positive and negative zero are considered different, while a NaN value is considered equal to other NaN values.
        Parameters:
        o1 - The first value to compare.
        o2 - The second value to compare.
        Returns:
        true if both values are equal.
        See Also:
        Float.equals(java.lang.Object)
      • equals

        public static boolean equals​(double o1,
                                     double o2)
        Returns true if the given doubles are equals. Positive and negative zero are considered different, while a NaN value is considered equal to other NaN values.
        Parameters:
        o1 - The first value to compare.
        o2 - The second value to compare.
        Returns:
        true if both values are equal.
        See Also:
        Double.equals(java.lang.Object)
      • equals

        public static boolean equals​(Object object1,
                                     Object object2)
                              throws AssertionError
        Convenience method for testing two objects for equality. One or both objects may be null. This method do not iterates recursively in array elements. If array needs to be compared, use one of Arrays method or deepEquals instead.

        Note on assertions: There is no way to ensure at compile time that this method is not invoked with array arguments, while doing so would usually be a program error. Performing a systematic argument check would impose a useless overhead for correctly implemented Object.equals(java.lang.Object) methods. As a compromise we perform this check at runtime only if assertions are enabled. Using assertions for argument check in a public API is usually a deprecated practice, but we make an exception for this particular method.

        Note on method overloading: This method could be selected by the compiler for comparing primitive types, because the compiler could perform an auto-boxing and get a result assignable to Object. However it should not occur in practice because overloaded (and more efficient) methods are provided for every primitive types. This is true even when the two arguments are different primitive type because of widening conversions. The only exception is when a boolean argument is mixed with a different primitive type.

        Parameters:
        object1 - The first object to compare, or null.
        object2 - The second object to compare, or null.
        Returns:
        true if both objects are equal.
        Throws:
        AssertionError - If assertions are enabled and at least one argument is an array.
      • deepEquals

        public static boolean deepEquals​(Object object1,
                                         Object object2)
        Convenience method for testing two objects for equality. One or both objects may be null. If both are non-null and are arrays, then every array elements will be compared.

        This method may be useful when the objects may or may not be array. If they are known to be arrays, consider using Arrays.deepEquals(Object[],Object[]) or one of its primitive counter-part instead.

        Rules for choosing an equals or deepEquals method

        • If both objects are declared as Object[] (not anything else like String[]), consider using Arrays.deepEquals(Object[],Object[]) except if it is known that the array elements can never be other arrays.
        • Otherwise if both objects are arrays (e.g. Expression[], String[], int[], etc.), use Arrays.equals(Object[],Object[]). This rule is applicable to arrays of primitive type too, since Arrays.equals is overriden with primitive counter-parts.
        • Otherwise if at least one object is anything else than Object (e.g. String, Expression, etc.), use equals(Object,Object). Using this deepEquals method would be an overkill since there is no chance that String or Expression could be an array.
        • Otherwise if both objects are declared exactly as Object type and it is known that they could be arrays, only then invoke this deepEquals method. In such case, make sure that the hash code is computed using deepHashCode(java.lang.Object) for consistency.
        Parameters:
        object1 - The first object to compare, or null.
        object2 - The second object to compare, or null.
        Returns:
        true if both objects are equal.
      • hash

        public static int hash​(boolean value,
                               int seed)
        Alters the given seed with the hash code value computed from the given value.
        Parameters:
        value - The value whose hash code to compute.
        seed - The hash code value computed so far. If this method is invoked for the first field, then any arbitrary value (preferrably different for each class) is okay.
        Returns:
        An updated hash code value.
      • hash

        public static int hash​(char value,
                               int seed)
        Alters the given seed with the hash code value computed from the given value.
        Parameters:
        value - The value whose hash code to compute.
        seed - The hash code value computed so far. If this method is invoked for the first field, then any arbitrary value (preferably different for each class) is okay.
        Returns:
        An updated hash code value.
      • hash

        public static int hash​(int value,
                               int seed)
        Alters the given seed with the hash code value computed from the given value. byte and short primitive types are handled by this method as well through implicit widening conversion.
        Parameters:
        value - The value whose hash code to compute.
        seed - The hash code value computed so far. If this method is invoked for the first field, then any arbitrary value (preferably different for each class) is okay.
        Returns:
        An updated hash code value.
      • hash

        public static int hash​(long value,
                               int seed)
        Alters the given seed with the hash code value computed from the given value. byte and short primitive types are handled by this method as well through implicit widening conversion.
        Parameters:
        value - The value whose hash code to compute.
        seed - The hash code value computed so far. If this method is invoked for the first field, then any arbitrary value (preferably different for each class) is okay.
        Returns:
        An updated hash code value.
      • hash

        public static int hash​(float value,
                               int seed)
        Alters the given seed with the hash code value computed from the given value.
        Parameters:
        value - The value whose hash code to compute.
        seed - The hash code value computed so far. If this method is invoked for the first field, then any arbitrary value (preferably different for each class) is okay.
        Returns:
        An updated hash code value.
      • hash

        public static int hash​(double value,
                               int seed)
        Alters the given seed with the hash code value computed from the given value.
        Parameters:
        value - The value whose hash code to compute.
        seed - The hash code value computed so far. If this method is invoked for the first field, then any arbitrary value (preferably different for each class) is okay.
        Returns:
        An updated hash code value.
      • hash

        public static int hash​(Object value,
                               int seed)
                        throws AssertionError
        Alters the given seed with the hash code value computed from the given value. The givan object may be null. This method do not iterates recursively in array elements. If array needs to be hashed, use one of Arrays method or deepHashCode instead.

        Note on assertions: There is no way to ensure at compile time that this method is not invoked with an array argument, while doing so would usually be a program error. Performing a systematic argument check would impose a useless overhead for correctly implemented Object.hashCode() methods. As a compromise we perform this check at runtime only if assertions are enabled. Using assertions for argument check in a public API is usually a deprecated practice, but we make an exception for this particular method.

        Parameters:
        value - The value whose hash code to compute, or null.
        seed - The hash code value computed so far. If this method is invoked for the first field, then any arbitrary value (preferably different for each class) is okay.
        Returns:
        An updated hash code value.
        Throws:
        AssertionError - If assertions are enabled and the given value is an array.
      • deepHashCode

        public static int deepHashCode​(Object object)
        Returns a hash code for the specified object, which may be an array. This method returns one of the following values:

        • If the supplied object is null, then this method returns 0.
        • Otherwise if the object is an array of objects, then Arrays.deepHashCode(Object[]) is invoked.
        • Otherwise if the object is an array of primitive type, then the corresponding Arrays.hashCode(...) method is invoked.
        • Otherwise Object.hashCode() is invoked.

        This method should be invoked only if the object type is declared exactly as Object, not as some subtype like Object[], String or float[]. In the later cases, use the appropriate Arrays method instead.

        Parameters:
        object - The object to compute hash code. May be null.
        Returns:
        The hash code of the given object.
      • deepToString

        public static String deepToString​(Object object)
        Returns a string representation of the specified object, which may be an array. This method returns one of the following values:

        • If the object is an array of objects, then Arrays.deepToString(Object[]) is invoked.
        • Otherwise if the object is an array of primitive type, then the corresponding Arrays.toString(...) method is invoked.
        • Otherwise String.valueOf(Object) is invoked.

        This method should be invoked only if the object type is declared exactly as Object, not as some subtype like Object[], Number or float[]. In the later cases, use the appropriate Arrays method instead.

        Parameters:
        object - The object to format as a string. May be null.
        Returns:
        A string representation of the given object.
      • emptyQueue

        public static <E> Queue<E> emptyQueue()
        Returns a queue which is always empty and accepts no element.
        Type Parameters:
        E - The type of elements in the empty collection.
        Returns:
        An empty collection.
        See Also:
        Collections.emptyList(), Collections.emptySet()
      • spaces

        public static String spaces​(int length)
        Returns a string of the specified length filled with white spaces. This method tries to return a pre-allocated string if possible.
        Parameters:
        length - The string length. Negative values are clamped to 0.
        Returns:
        A string of length length filled with white spaces.
      • ensureNonNull

        public static void ensureNonNull​(String name,
                                         Object object)
                                  throws NullPointerException
        Makes sure that an argument is non-null.
        Parameters:
        name - Argument name.
        object - User argument.
        Throws:
        NullPointerException - if object is null.
      • ensureArgumentNonNull

        public static void ensureArgumentNonNull​(String name,
                                                 Object object)
                                          throws IllegalArgumentException
        Makes sure that an argument is non-null and throws an IllegalArgumentException if it is.
        Parameters:
        name - argument name
        object - argument
        Throws:
        IllegalArgumentException - if object is null.
      • stream

        public static <T> Stream<T> stream​(Iterable<T> iterable)
        Creates a stream over the specified Iterable's elements.

        This operation is lazy in the sense that it does not iterate over the elements until the Stream is consumed.

        Type Parameters:
        T - the type of elements contained in the iterable
        Parameters:
        iterable - the iterable to stream over
        Returns:
        a stream over the iterable's elements
      • stream

        public static <T> Stream<T> stream​(Iterator<T> iterator)
        Creates a stream over the specified Iterator's elements.

        This operation is lazy in the sense that it does not iterate over the elements until the Stream is consumed.

        Type Parameters:
        T - the type of elements contained in the iterator
        Parameters:
        iterator - the iterator to stream over
        Returns:
        a stream over the iterator's elements
      • stream

        public static <T> Stream<T> stream​(Optional<T> optional)
        Creates a stream with zero or one element, depending on whether the specified Optional is empty or not.
        Type Parameters:
        T - the type of the element contained in the optional
        Parameters:
        optional - the optional to stream over
        Returns:
        a stream over the option's element or empty
      • streamIfSubtype

        public static <T,​U> Stream<Class<? extends U>> streamIfSubtype​(Class<T> type,
                                                                             Class<U> supertype)
        Creates a stream with zero or one elements, depending on whether the specified supertype is actually a supertype of the specified type (according to supertype.isAssignableFrom(type)).

        If the test is true, type is cast to a subclass of supertype and returned in the stream; otherwise the stream is empty.

        Type Parameters:
        T - the type of type
        U - the type of supertype
        Parameters:
        type - the type to cast
        supertype - the surmised supertype of type
        Returns:
        a stream over type cast to a subclass of supertype or empty
      • toUnmodifiableSet

        public static <T> Collector<T,​?,​Set<T>> toUnmodifiableSet()
        Type Parameters:
        T - the type of elements in the stream
        Returns:
        a Collector which collects elements into an unmodifiable Set
      • toInstanceByClassNameMap

        public static <T> Collector<T,​?,​Map<String,​T>> toInstanceByClassNameMap()
        Collects stream elements into a Map whose values are the stream elements and whose keys are those elements' fully qualified class names.

        If the stream contains several instances of the same class, only one of them will be present in the map. If the stream has an iteration order, the later elements win over earlier ones.

        Type Parameters:
        T - the type of elements in the stream
        Returns:
        a Collector which collects elements into a Map whose keys are class names and whose values are stream elements
      • assertNotZipSlipVulnarable

        public static final void assertNotZipSlipVulnarable​(File file,
                                                            Path destinationDir)
                                                     throws IOException
        Checks if the given filename exposes a zip slip vulnerability when it would be extracted to the given path.
        Parameters:
        file - name of the destination file to check, this should include the directories
        destinationDir - directory that the file would be unzipped to
        Throws:
        IOException - if the given fileName is found to be vulnerable to zip slip with respect to the destinationDir