简体   繁体   中英

Given that an Object is an Array of any type how do you test that it is empty in Java?

Please help me complete my isEmpty method:

public static boolean isEmpty(Object test){
    if (test==null){
        return true;
    }
    if (test.getClass().isArray()){
        //???
    }
    if (test instanceof String){
        String s=(String)test;
        return s=="";
    }
    if (test instanceof Collection){
        Collection c=(Collection)test;
        return c.size()==0;
    }
    return false;
}

What code would I put int to establish that if I am dealing with an array it will return true if it's length is zero? I want it to work no matter the type whether it is int[], Object[]. (Just so you know, I can tell you that if you put an int[] into an Object[] variable, it will throw an exception.)

You can use the helper method getLength(Object) from java.reflect.Array :

public static boolean isEmpty(Object test){
    if (test==null){
        return true;
    }
    if (test.getClass().isArray()){
        return 0 == Array.getLength(test);
    }
    if (test instanceof String){
        String s=(String)test;
        return s.isEmpty(); // Change this!!
    }
    if (test instanceof Collection){
        Collection c=(Collection)test;
        return c.isEmpty();
    }
    return false;
}

Note that you can't use

boolean empty = (someString == "");

because that is not safe. For comparing strings, use String.equals(String) , or in this case, just check if the length is zero.

You can use java.lang.reflect.Array#getLength .

Also note that your test for String won't work as you expect.

构建一些空检查的第三个选项是Apache的ArrayUtils

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM