2012-02-26 49 views
2

如何檢查這兩個數組陣列是否爲空?如何檢查二維數組是否爲空

這是我的代碼:

 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 

有誰有關於我的情況的IDE?

+3

部分代碼不見了不是嗎?如何從最多一個'System.out.println'獲得如此多的輸出? – 2012-02-26 12:13:15

+1

定義「空」。你的意思是'null'還是''「''? – 2012-02-26 12:15:19

+0

我想你不會發送完整的代碼。 – MJM 2012-02-26 12:17:26

回答

2

你在誤解我認爲Java的某些東西。當你寫:

String[][] user = new String[5][3]; 

user.length will always be 5 and 

user[0].length = user[1].length = ... = user[5].length = 3 

如果您要檢查,如果你的陣列中的所有值都emty你可以這樣做:

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 
1

我建議使用Apache Commons Lang3。在這個庫中存在用於處理數組的實用程序。 班級名稱爲ArrayUtils。對於樣本:

String[][] user = new String[5][3]; 
    for(String[] nestedArray : user) 
     if(ArrayUtils.isEmpty(nestedArray)) 
      System.out.println("Is empty"); 

Apache Commans Lang3是很好的實用程序。 有關更多信息,請參閱here