gad*_*dss 4 java multidimensional-array
如何检查这两个维度数组是否为空?
这是我的代码:
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");
}
Run Code Online (Sandbox Code Playgroud)
输出是:
5
empty null null null
Run Code Online (Sandbox Code Playgroud)
有没有人知道我的情况?
我认为您误解了 Java 中的某些内容。当你写:
String[][] user = new String[5][3];
user.length will always be 5 and
user[0].length = user[1].length = ... = user[5].length = 3
Run Code Online (Sandbox Code Playgroud)
如果您想检查数组中的所有值是否都是空值,您可以执行以下操作:
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");
}
Run Code Online (Sandbox Code Playgroud)
另一种解决方案是使用Arrays.deepEquals:
String[][] user = new String[5][3];
String[][] emptyReferenceForComparison= new String[5][3];
Arrays.deepEquals(user, emptyReferenceForComparison); // return true
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
24102 次 |
| 最近记录: |