【问题标题】:Finding Mode of a Data Set using HashMap and ArrayList. Can't figure it out [duplicate]使用 HashMap 和 ArrayList 查找数据集的模式。想不通[重复]
【发布时间】:2015-07-25 11:59:41
【问题描述】:

所以我试图创建一组方法来找到给它的一组整数的模式(以数组的形式),并返回一个包含所有模式的数组,包括没有的可能性模式。在大量调试之后,我坐下来编写这些 sn-ps 代码,但无法让它工作。代码的风格不是很好,但我只想知道是否有人能弄清楚出了什么问题。顺便说一句,main() 方法只是用来测试该方法。代码如下:

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));
}

结果:[I@677327b6。 我完全被难住了。有什么想法吗?

【问题讨论】:

  • “结果”是指[I@677327b6 被打印到控制台。而且,只是补充说明一下,没有编译器错误或类似的东西。只是出来的值很混乱。
  • 那是数组引用,见stackoverflow.com/questions/409784/…

标签: java debugging arraylist hashmap mode


【解决方案1】:

您可以使用Arrays.toString() 轻松打印出数组的内容:

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

您之前得到的结果[I@677327b6 是一个参考值。

【讨论】:

  • 感谢@tim,我想我只是错过了。再次感谢
猜你喜欢
  • 2018-03-03
  • 1970-01-01
  • 2016-11-16
  • 2020-04-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-18
  • 1970-01-01
  • 2015-03-20
相关资源
最近更新 更多