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.)
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With