【问题标题】:Printing Huffman Frequency Table打印霍夫曼频率表
【发布时间】:2019-05-01 03:10:13
【问题描述】:

我正在编写一些霍夫曼编码,我希望能够打印频率表。

但是,我尝试了下面的代码并得到了“不兼容的类型:条目无法转换为条目” for (Map.Entry entry : freq.entrySet())' 错误。有没有办法解决它,我可能能够显示频率表,它会更多地以表格或类似数组的形式而不是地图形式?

public static void buildHuffmanTree(String text)
{   // count frequency each character and store it in a map
    Map<Character, Integer> freq = new HashMap<>();
    for (int i = 0 ; i < text.length(); i++)
    {
        if (!freq.containsKey(text.charAt(i)))
        {
            freq.put(text.charAt(i), 0);
        }
        freq.put(text.charAt(i), freq.get(text.charAt(i)) + 1);
    }

    // Create a priority queue to store nodes of Huffman tree
    // Notice that highest priority item has lowest frequency
    PriorityQueue<Node> pq = new PriorityQueue<>((l, r) -> l.freq - 
    r.freq);

    for (Map.Entry<Character, String> entry : freq.entrySet())
    {
        System.out.println(entry.getKey() + " " + entry.getValue());
    }
}

【问题讨论】:

    标签: java huffman-code


    【解决方案1】:

    遍历entry set时,指定的值类型与实际hashmap中entry的值类型不匹配。每个条目的实际值类型是 Integer,但您当前在 for 循环中使用类型 String。所以我建议将 for 循环更改为

    for (Map.Entry<Character, Integer> entry : freq.entrySet())
    {
        System.out.println(entry.getKey() + " " + entry.getValue());
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多