Joe
Joe

Reputation: 8042

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.)

Upvotes: 9

Views: 193

Answers (3)

DefyGravity
DefyGravity

Reputation: 6011

A third option that builds in some null checks is Apache's ArrayUtils

Upvotes: 1

Martijn Courteaux
Martijn Courteaux

Reputation: 68857

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.

Upvotes: 9

Ismail Badawi
Ismail Badawi

Reputation: 37177

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

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

Upvotes: 8

Related Questions