1

So I'm trying to make a set of methods that find the mode of a set of ints given to it (in the form of an array), and return an array holding all of the modes, including the possibility of no modes. I sat down for a while writing these snippets of code and I couldn't get it to work, after extensive debugging. The code isn't in great style but I just want to know if anyone could figure out what is going wrong. By the way, the main() method is just there to test out the method. Here's the code:

public static int[] getMode(int[] numset) {
    Map<Integer, Integer> vals = new HashMap<Integer, Integer>();
    ArrayList<Integer> modes = new ArrayList<Integer>();
    int highCount = 0;

    for(int num : numset) {
        if(vals.containsKey(num))
            vals.put(num, vals.get(num) + 1);
        else
            vals.put(num, 0);       
    }

    if(allValuesEqual(vals)) return new int[0];

    for(int key : vals.keySet()) {
        if(vals.get(key) > highCount) {
            highCount = vals.get(key);
        }
    }

    for(int key : vals.keySet()) {
        if(vals.get(key) == highCount)
            modes.add(key);
    }

    int[] mode = new int[modes.size()];
    int count = 0;
    for(int num : modes) {
        mode[count] = num;
        count++;
    }


    return mode;
}

private static boolean allValuesEqual(Map<Integer,Integer> vmap) {
    ArrayList<Integer> a = new ArrayList<Integer>();
    for(int key : vmap.keySet()) {
        a.add(vmap.get(key));
    }

    for(int i = 0, n = a.size(); i < n; i++) {
        if(a.get(i) != a.get(0) && i != 0)
            return false;
    }
    return true;
}

public static void main(String[] args) {
    int[] array = {6,10,10};
    System.out.println(getMode(array));
}

The result: [I@677327b6. I am utterly stumped. Any ideas?

jake
  • 124
  • 1
  • 10
  • By "the result" I mean that `[I@677327b6` was printed to the console. And also, just o add clarification, there were no compiler errors or anything like that. It is just the value that is coming out is very confusing. – jake May 14 '15 at 01:11
  • 1
    that's the array reference, see this http://stackoverflow.com/questions/409784/whats-the-simplest-way-to-print-a-java-array – guido May 14 '15 at 01:13

1 Answers1

0

You can use Arrays.toString() to easily print out the contents of your array:

public static void main(String[] args) {
    int[] array = {6,10,10};
    System.out.println(Arrays.toString(getMode(array)));
}

The previous result you were getting [I@677327b6 was a reference value.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360