Given that an object is an array of any type, how to test that it is empty in Java?

Please help me fill in 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 will I use to determine if I am processing an array and if its length is zero, it will return true? I want it to work, whether the type is int [], object [] (just you know, I can tell you that if you put an int [] into an object [] variable, it will throw an exception.)

Solution

You can use Java reflect. Helper method getlength (object) in 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;
}

Please note that you cannot use

boolean empty = (someString == "");

Because it's not safe To compare strings, use string Equals (string), or in this case, just check if the length is zero

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>