Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

arrays

types

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

like image 244
Joe Avatar asked Jan 30 '12 17:01

Joe


People also ask

How do you check the array is empty or not in Java?

The isEmpty() method of ArrayList in java is used to check if a list is empty or not. It returns true if the list contains no elements otherwise it returns false if the list contains any element.

How do you check if an array is empty?

To check if an array is empty or not, you can use the .length property. The length property sets or returns the number of elements in an array. By knowing the number of elements in the array, you can tell if it is empty or not. An empty array will have 0 elements inside of it.

How do you check if an object is an instance of an array?

isArray() method is used to check if an object is an array. The Array. isArray() method returns true if an object is an array, otherwise returns false . Note: For an array, the typeof operator returns an object.

How do you check if something is an element of an array Java?

contains() method in Java is used to check whether or not a list contains a specific element. To check if an element is in an array, we first need to convert the array into an ArrayList using the asList() method and then apply the same contains() method to it​.


1 Answers

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.

like image 102
Martijn Courteaux Avatar answered Oct 23 '22 20:10

Martijn Courteaux