使用HashMap

时间:2017-05-07 18:48:26

标签: java

我被赋予了一个用于构建霍夫曼树的任务,以便为我的数据结构类的文件编码字符串,但是我遇到了一些麻烦。我知道如何构建树并对值进行编码,但我需要构建一个节点数组,然后将其放入排序列表中。 我写了一个for循环,迭代遍历节点数组的长度,并嵌套一个遍历HashMap的foreach循环。问题在于为每个角色创建每个新节点。我的代码似乎没有将所有值添加到数组中,我尝试了多个不同的循环,但它们都产生类似的结果。我有一个创建两个数组的想法,一个用于键,一个用于值,我可以传递给节点构造函数,但这并不能真正起作用。

以下是节点的类:

public class HuffmanTreeNode {
    public char key;
    public int value;
    public HuffmanTreeNode nextNode = null;
    public HuffmanTreeNode leftChild = null;
    public HuffmanTreeNode rightChild = null;

    public HuffmanTreeNode(char k, int v) {
        key = k;
        value = v;
    }

    public HuffmanTreeNode(HuffmanTreeNode left, HuffmanTreeNode right) {
        leftChild = left;
        rightChild = right;

        value = rightChild.value + leftChild.value;
    }

    public boolean isLeaf() {
        if (leftChild == null && rightChild == null) {
            return true;
        }

        return false;
    }
}

这是构建节点数组的代码:

HashMap<Character, Integer> frequencies = new HashMap<Character, Integer>();
    for (String s : fileContents) {
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            Integer value = frequencies.get(new Character(c));

            if (value != null) {
                frequencies.put(c, new Integer(value + 1));
            } else {
                frequencies.put(c, 1);
            }
        }
    }

    char[] chars = new char[frequencies.size()];
    int[] freq = new int[frequencies.size()];

    for (int i = 0; i < frequencies.size(); i++) {
        for (HashMap.Entry<Character, Integer> entry : frequencies.entrySet()) {
            chars[i] = entry.getKey();
            freq[i] = entry.getValue();
        }
    }

    for (int i = 0; i < frequencies.size(); i++) {
        System.out.println(chars[i] + " " + freq[i]);
    }


    SortedList sortedList = new SortedList();
    HuffmanTreeNode[] nodes = new HuffmanTreeNode[frequencies.size()];

    for (int i = 0; i < nodes.length; i++) {
        nodes[i] = new HuffmanTreeNode(chars[i], freq[i]);
    }

1 个答案:

答案 0 :(得分:0)

我实际上只是通过更改循环来修复我的代码:

for (int i = 0; i < frequencies.size(); i++) {
    for (HashMap.Entry<Character, Integer> entry : frequencies.entrySet()) {
        chars[i] = entry.getKey();
        freq[i] = entry.getValue();
    }
}

到:

int index = 0;
    for (HashMap.Entry<Character, Integer> entry : frequencies.entrySet()) {
        chars[index] = entry.getKey();
        freq[index] = entry.getValue();
        index++;
    }