[英]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: 请帮我完成我的isEmpty方法:
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? 我将int设置为什么代码来确定如果我正在处理一个数组,如果它的长度为零,它将返回true? I want it to work no matter the type whether it is int[], Object[].
无论类型是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.)
(大家都知道,我可以告诉你,如果你把一个int []放到一个Object []变量中,它会抛出异常。)
You can use the helper method getLength(Object)
from java.reflect.Array
: 您可以使用
java.reflect.Array
的helper方法getLength(Object)
:
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. 要比较字符串,请使用
String.equals(String)
,或者在这种情况下,只检查长度是否为零。
You can use java.lang.reflect.Array#getLength
. 您可以使用
java.lang.reflect.Array#getLength
。
Also note that your test for String
won't work as you expect. 另请注意,您对
String
的测试将无法按预期工作。
构建一些空检查的第三个选项是Apache的ArrayUtils
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.