how can I check if this two dimentinal array is empty?
this is my code :
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");
}
and the output is :
5
empty null null null
Does anyone have an ide about my situation?
3 Answers 3
You are misunderstanding something in Java I think. When you write :
String[][] user = new String[5][3];
user.length will always be 5 and
user[0].length = user[1].length = ... = user[5].length = 3
If you want to check if all value in your array are emty you can do something like :
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");
}
Another solution would be to use Arrays.deepEquals
:
String[][] user = new String[5][3];
String[][] emptyReferenceForComparison= new String[5][3];
Arrays.deepEquals(user, emptyReferenceForComparison); // return true
I suggest using Apache Commons Lang3. In this library exist utility for working with arrays.
Name of the class is ArrayUtils
. For sample:
String[][] user = new String[5][3];
for(String[] nestedArray : user)
if(ArrayUtils.isEmpty(nestedArray))
System.out.println("Is empty");
Apache Commans Lang3 is good utility. see here for more informations.
Sometimes during competitive programming problems, in order to handle the corner case some code like in the snippet below would be necessary. Just checking matrix.length==0
will not work since it gives only whether the row is empty but there might be a column present in it.
if(matrix.length < 1 || matrix[0].length < 1) {
return true; //empty
}
-
You're welcome. I am here to help :) Thanks for your feedback.Antares– Antares2020年05月11日 23:18:51 +00:00Commented May 11, 2020 at 23:18
System.out.println
?null
or""
?