1

I made this method that takes an array of arrays and should return the array most frequent in my array of arrays, but it does print only a[0], which means that one of my expressions doesn't get evaluated. I don't understand which and why.

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
  • did you try a[z].length? Commented Mar 25, 2014 at 18:06

1 Answer 1

4

You cannot compare two different arrays for element-by-element equality with this expression:

temp == a[j]

This checks reference equality only, meaning that it evaluates true only when temp is literally the same array object.

In order to fix this, replace with a call of Arrays.equals(temp, a[j])

Sign up to request clarification or add additional context in comments.

2 Comments

So I should loop through each elements, instead?
@GeorgeIrimiciuc Essentially, yes. The need to do that is so pervasive among Java programmers, though, that Java designers have added an API to dot that (see the update to the answer).

Your Answer

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.