5

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?

asked Feb 26, 2012 at 12:11
3
  • 3
    Some code is missing isn't it? How do you get so much output from at most one System.out.println? Commented Feb 26, 2012 at 12:13
  • 1
    Define "empty". Do you mean null or ""? Commented Feb 26, 2012 at 12:15
  • I think you don't send complete your code. Commented Feb 26, 2012 at 12:17

3 Answers 3

6

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
answered Feb 26, 2012 at 12:23
1

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.

answered Feb 26, 2012 at 12:26
0

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
}
Antares
6813 silver badges16 bronze badges
answered May 10, 2020 at 17:42
1
  • You're welcome. I am here to help :) Thanks for your feedback. Commented May 11, 2020 at 23:18

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.