最常见的数组数组

时间:2014-03-25 18:04:13

标签: java arrays

我创建了这个采用数组数组的方法,并且应该在我的数组数组中最频繁地返回数组,但是它只打印一个[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;
}

1 个答案:

答案 0 :(得分:4)

您无法将两个不同的数组与此表达式进行逐元素相等的比较:

temp == a[j]

这仅检查引用相等,这意味着它仅在true字面上是同一个数组对象时评估temp

要解决此问题,请拨打Arrays.equals(temp, a[j])