两种方法之间有一个关键的区别
null
数组和空数组。这是一个测试
无效的
.
int arr[] = null;
if (arr == null) {
System.out.println("array is null");
}
这里的“空”没有正式意义。我选择将空定义为有0个元素:
arr = new int[0];
if (arr.length == 0) {
System.out.println("array is empty");
}
“空”的另一种定义是如果所有元素
无效的
Object arr[] = new Object[10];
boolean empty = true;
for (int i=0; i<arr.length; i++) {
if (arr[i] != null) {
empty = false;
break;
}
}
或
Object arr[] = new Object[10];
boolean empty = true;
for (Object ob : arr) {
if (ob != null) {
empty = false;
break;
}
}