Class Utilities
- Object
-
- Utilities
-
public final class Utilities extends Object
Miscellaneous methods, including cnvenience methods forequalsandhashCodeimplementations. Example use case in a class calledCar: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 ofArraysmethod for comparing arrays.This class also provides convenience methods for computing hash code values. All those methods expect a
seedargument, 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) serialVersionUIDfor example.- Since:
- 2.5
- Author:
- Martin Desruisseaux (IRD)
-
-
Method Summary
All Methods Static Methods Concrete Methods Modifier and Type Method Description static voidassertNotZipSlipVulnarable(File file, Path destinationDir)Checks if the given filename exposes a zip slip vulnerability when it would be extracted to the given path.static booleandeepEquals(Object object1, Object object2)Convenience method for testing two objects for equality.static intdeepHashCode(Object object)Returns a hash code for the specified object, which may be an array.static StringdeepToString(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 voidensureArgumentNonNull(String name, Object object)Makes sure that an argument is non-null and throws anIllegalArgumentExceptionif it is.static voidensureNonNull(String name, Object object)Makes sure that an argument is non-null.static booleanequals(boolean o1, boolean o2)Returnstrueif the given booleans are equals.static booleanequals(byte o1, byte o2)Returnstrueif the given bytes are equals.static booleanequals(char o1, char o2)Returnstrueif the given characters are equals.static booleanequals(double o1, double o2)Returnstrueif the given doubles are equals.static booleanequals(float o1, float o2)Returnstrueif the given floats are equals.static booleanequals(int o1, int o2)Returnstrueif the given integers are equals.static booleanequals(long o1, long o2)Returnstrueif the given longs are equals.static booleanequals(short o1, short o2)Returnstrueif the given shorts are equals.static booleanequals(Object object1, Object object2)Convenience method for testing two objects for equality.static inthash(boolean value, int seed)Alters the given seed with the hash code value computed from the given value.static inthash(char value, int seed)Alters the given seed with the hash code value computed from the given value.static inthash(double value, int seed)Alters the given seed with the hash code value computed from the given value.static inthash(float value, int seed)Alters the given seed with the hash code value computed from the given value.static inthash(int value, int seed)Alters the given seed with the hash code value computed from the given value.static inthash(long value, int seed)Alters the given seed with the hash code value computed from the given value.static inthash(Object value, int seed)Alters the given seed with the hash code value computed from the given value.static Stringspaces(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 specifiedIterable's elements.static <T> Stream<T>stream(Iterator<T> iterator)Creates a stream over the specifiedIterator's elements.static <T> Stream<T>stream(Optional<T> optional)Creates a stream with zero or one element, depending on whether the specifiedOptionalis 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 specifiedsupertypeis actually a supertype of the specifiedtype(according tosupertype.isAssignableFrom(type)).static <T> Collector<T,?,Map<String,T>>toInstanceByClassNameMap()Collects stream elements into aMapwhose values are the stream elements and whose keys are those elements' fully qualified class names.static <T> Collector<T,?,Set<T>>toUnmodifiableSet()
-
-
-
Method Detail
-
equals
public static boolean equals(boolean o1, boolean o2)Returnstrueif the given booleans are equals. This overloaded flavor is provided only for allowing developper to invokeequalsmethods without consideration for the argument type.- Parameters:
o1- The first value to compare.o2- The second value to compare.- Returns:
trueif both values are equal.- See Also:
Boolean.equals(java.lang.Object)
-
equals
public static boolean equals(char o1, char o2)Returnstrueif the given characters are equals. This overloaded flavor is provided only for allowing developper to invokeequalsmethods without consideration for the argument type.- Parameters:
o1- The first value to compare.o2- The second value to compare.- Returns:
trueif both values are equal.- See Also:
Character.equals(java.lang.Object)
-
equals
public static boolean equals(byte o1, byte o2)Returnstrueif the given bytes are equals. This overloaded flavor is provided only for allowing developper to invokeequalsmethods without consideration for the argument type.- Parameters:
o1- The first value to compare.o2- The second value to compare.- Returns:
trueif both values are equal.- See Also:
Byte.equals(java.lang.Object)
-
equals
public static boolean equals(short o1, short o2)Returnstrueif the given shorts are equals. This overloaded flavor is provided only for allowing developper to invokeequalsmethods without consideration for the argument type.- Parameters:
o1- The first value to compare.o2- The second value to compare.- Returns:
trueif both values are equal.- See Also:
Short.equals(java.lang.Object)
-
equals
public static boolean equals(int o1, int o2)Returnstrueif the given integers are equals. This overloaded flavor is provided only for allowing developper to invokeequalsmethods without consideration for the argument type.- Parameters:
o1- The first value to compare.o2- The second value to compare.- Returns:
trueif both values are equal.- See Also:
Integer.equals(java.lang.Object)
-
equals
public static boolean equals(long o1, long o2)Returnstrueif the given longs are equals. This overloaded flavor is provided only for allowing developper to invokeequalsmethods without consideration for the argument type.- Parameters:
o1- The first value to compare.o2- The second value to compare.- Returns:
trueif both values are equal.- See Also:
Long.equals(java.lang.Object)
-
equals
public static boolean equals(float o1, float o2)Returnstrueif 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:
trueif both values are equal.- See Also:
Float.equals(java.lang.Object)
-
equals
public static boolean equals(double o1, double o2)Returnstrueif 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:
trueif 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 ofArraysmethod ordeepEqualsinstead.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 abooleanargument is mixed with a different primitive type.- Parameters:
object1- The first object to compare, ornull.object2- The second object to compare, ornull.- Returns:
trueif 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
equalsordeepEqualsmethod- If both objects are declared as
Object[](not anything else likeString[]), consider usingArrays.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.), useArrays.equals(Object[],Object[]). This rule is applicable to arrays of primitive type too, sinceArrays.equalsis overriden with primitive counter-parts. - Otherwise if at least one object is anything else than
Object(e.g.String,Expression, etc.), useequals(Object,Object). Using thisdeepEqualsmethod would be an overkill since there is no chance thatStringorExpressioncould be an array. - Otherwise if both objects are declared exactly as
Objecttype and it is known that they could be arrays, only then invoke thisdeepEqualsmethod. In such case, make sure that the hash code is computed usingdeepHashCode(java.lang.Object)for consistency.
- Parameters:
object1- The first object to compare, ornull.object2- The second object to compare, ornull.- Returns:
trueif both objects are equal.
- If both objects are declared as
-
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.byteandshortprimitive 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.byteandshortprimitive 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 ofArraysmethod ordeepHashCodeinstead.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, ornull.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 likeObject[],Stringorfloat[]. In the later cases, use the appropriateArraysmethod instead.- Parameters:
object- The object to compute hash code. May benull.- Returns:
- The hash code of the given object.
- If the supplied object is
-
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 likeObject[],Numberorfloat[]. In the later cases, use the appropriateArraysmethod instead.- Parameters:
object- The object to format as a string. May benull.- Returns:
- A string representation of the given object.
- If the object is an array of objects, then
-
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
lengthfilled 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- ifobjectis null.
-
ensureArgumentNonNull
public static void ensureArgumentNonNull(String name, Object object) throws IllegalArgumentException
Makes sure that an argument is non-null and throws anIllegalArgumentExceptionif it is.- Parameters:
name- argument nameobject- argument- Throws:
IllegalArgumentException- ifobjectis null.
-
stream
public static <T> Stream<T> stream(Iterable<T> iterable)
Creates a stream over the specifiedIterable'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 specifiedIterator'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 specifiedOptionalis 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 specifiedsupertypeis actually a supertype of the specifiedtype(according tosupertype.isAssignableFrom(type)).If the test is
true,typeis cast to a subclass ofsupertypeand returned in the stream; otherwise the stream is empty.- Type Parameters:
T- the type oftypeU- the type ofsupertype- Parameters:
type- the type to castsupertype- the surmised supertype oftype- Returns:
- a stream over
typecast to a subclass ofsupertypeor empty
-
toUnmodifiableSet
public static <T> Collector<T,?,Set<T>> toUnmodifiableSet()
- Type Parameters:
T- the type of elements in the stream- Returns:
- a
Collectorwhich collects elements into an unmodifiableSet
-
toInstanceByClassNameMap
public static <T> Collector<T,?,Map<String,T>> toInstanceByClassNameMap()
Collects stream elements into aMapwhose 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
Collectorwhich collects elements into aMapwhose 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 directoriesdestinationDir- directory that the file would be unzipped to- Throws:
IOException- if the givenfileNameis found to be vulnerable to zip slip with respect to thedestinationDir
-
-