Java 使用 String[] 数组进行空检查
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22162231/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Empty check with String[] array
提问by Piolo Opaw
I want to know the best practice for checking whether a string array is empty or not.
我想知道检查字符串数组是否为空的最佳实践。
String[] name = {"a" , "b"};
if (name == null) {
}
Is this a good practice or there are more best codes for the same?
这是一个好的做法还是有更多的最佳代码?
采纳答案by Solace
To check if a string array is empty...
要检查字符串数组是否为空...
public boolean isEmptyStringArray(String [] array){
for(int i=0; i<array.length; i++){
if(array[i]!=null){
return false;
}
}
return true;
}
回答by Aditya
if(name!=null && name.length > 0) {
// This means there are some elements inside name array.
} else {
// There are no elements inside it.
}
回答by Oleg Estekhin
All arrays in Java have a special field "length" that contains the number of elements in the array, that is array length in other words.
Java 中的所有数组都有一个特殊字段“length”,它包含数组中元素的数量,即数组长度。
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";
}
To test whether the array contains a null element or an empty string you need to iterate through it and check each element individually.
要测试数组是否包含空元素或空字符串,您需要遍历它并单独检查每个元素。
Do not forget that the length of array is the special field array.legnth and the length of the string is the function string.length().
不要忘记数组的长度是特殊字段array.legnth,字符串的长度是函数string.length()。
回答by Adrian Shum
Normally you would want to do something like:
通常你会想要做这样的事情:
if (arr != null && arr.length > 0) { ... }
for non-empty array.
对于非空数组。
However, as you may suspect, someone have made utils for such kind of common action. For example, in Commons-lang, you can do something like:
但是,正如您可能怀疑的那样,有人已经为此类常见操作制作了实用程序。例如,在 Commons-lang 中,您可以执行以下操作:
if (ArrayUtils.isEmpty(arr)) {... }
if you do a static import for ArrayUtils.isEmpty
, this line can be even shorter and looks nicer:
如果您对 进行静态导入ArrayUtils.isEmpty
,则此行可以更短且看起来更好:
if (isEmpty(arr)) { ... }