我想知道检查字符串数组是否为空的最佳做法。使用String []数组进行空检查
String[] name = {"a" , "b"};
if (name == null) {
}
这是一个很好的做法,还是有更好的代码?
我想知道检查字符串数组是否为空的最佳做法。使用String []数组进行空检查
String[] name = {"a" , "b"};
if (name == null) {
}
这是一个很好的做法,还是有更好的代码?
要检查一个字符串数组是空的...
public boolean isEmptyStringArray(String [] array){
for(int i=0; i<array.length; i++){
if(array[i]!=null){
return false;
}
}
return true;
}
if(name!=null && name.length > 0) {
// This means there are some elements inside name array.
} else {
// There are no elements inside it.
}
Java中的所有阵列具有特殊领域的“长度”,其中包含数组中元素的个数,即数组长度换一种说法。
String test(String[] array)
{
if (array == null) {
return "array is null";
}
if (array.length == 0) {
return "array is empty, meaning it has no element";
}
for (String s : array) {
if (s == null) {
return "array contains null element";
}
if (s.length() == 0) {
return "array contains empty string";
}
// or
if (s.isEmpty()) {
return "array contains empty string";
}
}
return "array is not null or empty and does not contain null or empty strings";
}
要测试数组是否包含空元素或空字符串,您需要遍历它并逐个检查每个元素。
不要忘记,数组的长度是特殊字段array.legnth,字符串的长度是函数string.length()。
通常你会想要做的事,如:
if (arr != null && arr.length > 0) { ... }
非空数组。
但是,正如您可能会怀疑的那样,有人已经为这种常见操作制作了utils。例如,在下议院琅,你可以这样做:
if (ArrayUtils.isEmpty(arr)) {... }
,如果你做ArrayUtils.isEmpty
静态导入,这条线还可以更短,看起来更好:
if (isEmpty(arr)) { ... }
org.apache.commons.lang.ArrayUtils这将更有用如果项目已经使用** apache包**,通常简单的编程不使用该jar分发 –
@SrinathGanesh当然是否使用第三方lib是选择的OP,但使用Maven和Gradle等现代构建工具,在简单程序中使用这样的lib没有任何问题。 –
你是什么意思通过“布尔值的String []?”你认为什么是真实的,你认为什么是错误的? –
我认为“布尔值的String []”的概念根本不适用于Java。它不像JavaScript那里的东西是真的或是狡猾的。您可以检查引用是否为空,或者数组的元素是否为空,但这就是全部。 – ktm5124