2011-09-19 81 views
0
TreeNode[] children = grid[row][col].getChildren(); 

我想一個簡單的函數,能告訴我有多少個對象在此數組中? getChildren()將返回大小沒有大於4的對象,例如:像array.length函數不包含NULL元素?

children[0] = null; 
children[1] = TreeNode Object 
children[2] = null; 
children[3] = null; 
+0

所以你會想'children.mySizeMethod()'返回4或1(或別的東西,Ë VEN)? –

+0

考慮使用'List'或'Map'代替普通老式陣列。 Collections API提供了許多有用的類和方法。 – BalusC

+0

(@BalusC - 真的......但有沒有「有多少非空元素」的方法......假設這就是他的詢問。) –

回答

4

你爲什麼不把它寫自己:

public static <T> int getLength(T[] arr){ 
    int count = 0; 
    for(T el : arr) 
     if (el != null) 
      ++count; 
    return count; 
} 
0

這應該工作。基本上與爲您編寫的函數相同,而不是特定的TreeNode。

int initLength(Object[] myArray) { 
    int count = 0; 
    for (Object obj : myArray) { 
    if (obj != null) count++; 
    } 
    return count; 
} 

我把它稱爲initLength,因爲這些項目是init'd,但稱它爲你喜歡的。有些人會說,當你定義它的時候,它是init'd,無論內容是否爲空。

0

其他替代:

ArrayList l = new ArrayList(Arrays.asList(children)); 
l.removeAll(Collections.singleton(null)); 
l.size(); 
0

或許矯枉過正使用謂詞,但這裏有一個番石榴解決方案:

int numNotNull = Iterables.size(Iterables.filter(Arrays.asList(children), 
         Predicates.notNull())); 
0

在Java 8中,您可以使用Math.toIntExactArrays.stream構建一個漂亮的單行:

Math.toIntExact(Arrays.stream(row).filter(s -> s != null).count()) 
+0

有誰知道這是不是更好,性能明智的,比自己寫一個循環? –

+1

幾乎肯定不是。由於數組已經被分配,所以你不會看到使用流的任何性能改進。當這種事情真正的亮點,當你從如文件或套接字的I/O流(或一些其他類型的來源可以閱讀懶洋洋的)讀的 – mumrah