So I want to create a method that validates that two Arrays are of same length like:
validateSameSize(Object[] first, Object[] second) {
if (first.length != second.length) throw new Exception();
}
The problem is that this method only works for non-primitive Arrays. If I want to compare a char
-Array with another array this does not work. Is there a way to implement this function without too much overhead?
I have already tried
<T,V> validateSameSize(T[] first, V[] second)
but since generics also need a class and don't work with primitive types, this does not work. Also
validateSameSize(Array first, Array second)
doesn't work either
You can use Array#getLength
:
public static boolean sameSize(Object arrayA, Object arrayB) {
return Array.getLength(arrayA) == Array.getLength(arrayB);
}
It will work with non-primitive arrays as well as with primitive ones:
System.out.println(sameSize(new int[0], new int[100])); // false
System.out.println(sameSize(new char[0], new int[0])); // true
System.out.println(sameSize(new Object[0], new Object[0])); // true
System.out.println(sameSize(new Object[0], new List[0])); // true
Also don't forget that passing an Object
that is not an array to Array#getLength
will result in IllegalArgumentException
.
This code:
Object notArray = 100;
System.out.println(Array.getLength(notArray));
produces:
Exception in thread "main" java.lang.IllegalArgumentException: Argument is not an array
If you need to fail fast before invoking Array#getLength
you can check if the argument is actually array:
if (!object.getClass().isArray()) {
// object is not array. Do something with it
}
The caco3 answer is fine.
Note that if the Object
params are not arrays you will discover it only at runtime.
A safer way would be to overload the method for primitives :
void validateSameSize(Object[] first, Object[] second) throws Exception {
if (first.length != second.length) throw new Exception();
}
void validateSameSize(int[] first, int[] second) throws Exception {
if (first.length != second.length) throw new Exception();
}
And so for...
It will require you to write more code but your code would be more robust.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With