如何检查这个二维数组是否为空?
这是我的代码:
String[][] user = new String[5][3];
System.out.print(user.length);
if (user.length == 5 ){
System.out.print("\n empty");
}
for (int j=0; j<3; j++) {
System.out.print(" " + user[0][j]+ "\n");
}
输出是:
5
empty null null null
有人知道我的情况吗?
最佳答案
我认为您误解了 Java 中的某些内容。当你写的时候:
String[][] user = new String[5][3];
user.length will always be 5 and
user[0].length = user[1].length = ... = user[5].length = 3
如果你想检查数组中的所有值是否为空,你可以这样做:
boolean notNull = false;
for(String[] array : user){
for(String val : array){
if(val!=null){
notNull=true;
break;
}
}
}
if(notNull){
System.out.println("Array not empty)";
}else{
System.out.println("Array empty");
}
另一种解决方案是使用 Arrays.deepEquals
:
String[][] user = new String[5][3];
String[][] emptyReferenceForComparison= new String[5][3];
Arrays.deepEquals(user, emptyReferenceForComparison); // return true
关于java - 如何检查二维数组是否为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9452933/