I'd like to create a method that checks every Object's value is empty.If the input object is null then return true;.If input is type of array, check it's length. Below is my method to implement this logic
public static boolean isEmpty(Object input) {
if (input == null) {
return true;
}
if (input instanceof Collection) {
if (((Collection<?>) input).size() == 0) {
return true;
}
}
if (input instanceof String) {
if (((String) input).trim().length() == 0) {
return true;
}
}
if (input instanceof Object[]) {
if (((Object[]) input).length == 0) {
return true;
}
}
return false;
}
But the problem is while I testing as like this
int[] a = {};
float[] b = {};
Integer[] c = {};
Float[] d = {};
System.out.println(Validator.isEmpty(a));
System.out.println(Validator.isEmpty(b));
System.out.println(Validator.isEmpty(c));
System.out.println(Validator.isEmpty(d));
I have no idea why a and b are false. Can somebody explain me ?
new float[0] instanceof Object[]?isEmptymethods which take different type arguments?Incompatible conditional operand types float[] and Object[]isEmptymethod for all primitive array typesCharSequenceinstead of justString. This will catch not only String but also StringBuilder and many other string-like objects.