2014-03-25 74 views
1

我做了這個方法,它接受一個數組數組,並且應該返回數組中最頻繁的數組,但它只打印一個[0],這意味着我的一個表達式不會被評估。我不明白哪些和爲什麼。陣列數組的最頻繁陣列

private static int[] frequency(int[][] a) { 
    for (int z = 0; z < a.length; z++) { 
     for (int t = 0; t < a[1].length; t++) { 
      System.out.print(a[z][t]+" "); 

     }System.out.println();} 
    int count = 1, tempCount; 
    int[] popular = a[0]; 
    int[] temp; 
    for (int i = 0; i < a.length; i++) { 
     temp = a[i]; 
     tempCount = 0; 
     for (int j = 0; j < a.length; j++) { 
      if ((temp == a[j])&&(i!=j)) { 
       tempCount++; 
      } 

     } 
     if (tempCount > count) { 
      popular = temp; 
      count = tempCount; 

     } 
    } 

    return popular; 
} 
+0

替換了你試過的[z] .length? – mac10688

回答

4

不能比較對元件逐元件平等兩個不同的陣列,此表達式:

temp == a[j] 

這僅檢查引用相等,這意味着它的計算結果true只有當temp是字面上相同的數組對象。

爲了解決這個問題,用Arrays.equals(temp, a[j])

+0

所以我應該循環遍歷每個元素,而不是? –

+0

@GeorgeIrimiciuc基本上,是的。儘管如此,Java程序員普遍需要這樣做,因爲Java設計人員已經添加了一個API來標記它(請參閱答案的更新)。 – dasblinkenlight