Cataclysm
Cataclysm

Reputation: 8578

How to check primitive empty array

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 ?

Upvotes: 0

Views: 779

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074355

float[] is not instanceof Object[]. If you want to check for all kinds of arrays, you probably want to get the class from the object and check its isArray method. Then you can use Array.getLength to get its length (since, bizarrely, you can't use Class#getField to get the length field):

import java.lang.reflect.*;

class Validator {
    public static void main(String args[]) throws Exception {
        int[] a = {};
        float[] b = {};
        Integer[] c = {};
        Float[] d = {};
        System.out.println(Validator.isEmpty(a));            // true
        System.out.println(Validator.isEmpty(b));            // true
        System.out.println(Validator.isEmpty(c));            // true
        System.out.println(Validator.isEmpty(d));            // true
        System.out.println(Validator.isEmpty(new float[3])); // false (just double-checking)
    }

    public static boolean isEmpty(Object input) {
        if (input == null) {
            return true;
        }
        if (input instanceof String) {
            if (((String) input).trim().length() == 0) {
                return true;
            }
        }
        if (input.getClass().isArray()) {
            return Array.getLength(input) == 0;
        }
        return false;
    }
}

Upvotes: 5

Related Questions