ArrayList作为HashMap中的键 [英] ArrayList as key in HashMap

查看:100
本文介绍了ArrayList作为HashMap中的键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以添加 ArrayList 作为 HashMap 的关键字。我想保持bigrams的频率计数。这个bigram是关键,价值就在于它的频率。

Would it be possible to add an ArrayList as the key of HashMap. I would like to keep the frequency count of bigrams. The bigram is the key and the value is its frequency.

对于像他是这样的每个bigrams,我创建一个 ArrayList 并将其插入到 HashMap 中。但是我没有得到正确的输出。

For each of the bigrams like "he is", I create an ArrayList for it and insert it into the HashMap. But I am not getting the correct output.

public HashMap<ArrayList<String>, Integer> getBigramMap(String word1, String word2) {
    HashMap<ArrayList<String>, Integer> hm = new HashMap<ArrayList<String>, Integer>();
    ArrayList<String> arrList1 = new ArrayList<String>();
    arrList1 = getBigram(word1, word2);
    if (hm.get(arrList1) != null) {
        hm.put(arrList1, hm.get(arrList1) + 1);
    } else {
        hm.put(arrList1, 1);
    }
    System.out.println(hm.get(arrList1));
    return hm;
}


public ArrayList<String> getBigram(String word1, String word2) {
    ArrayList<String> arrList2 = new ArrayList<String>();
    arrList2.add(word1);
    arrList2.add(word2);
    return arrList2;
}


推荐答案

是的,您可以拥有 ArrayList 作为哈希映射中的键,但它是非常糟糕的主意,因为它们是可变的

Yes you can have ArrayLists as a keys in a hash map, but it is a very bad idea since they are mutable.

如果以任何方式(或其任何元素)更改 ArrayList ,映射基本上会丢失,因为键不会像它插入时那样具有相同的 hashCode

If you change the ArrayList in any way (or any of its elements), the mapping will basically be lost, since the key won't have the same hashCode as it had when it was inserted.

经验法则是在散列映射中只使用不可变数据类型作为键。正如Alex Stybaev所建议的那样,您可能想创建一个 Bigram 类,如下所示:

The rule of thumb is to use only immutable data types as keys in a hash map. As suggested by Alex Stybaev, you probably want to create a Bigram class like this:

final class Bigram {

    private final String word1, word2;

    public Bigram(String word1, String word2) {
        this.word1 = word1;
        this.word2 = word2;
    }

    public String getWord1() {
        return word1;
    }

    public String getWord2() {
        return word2;
    }

    @Override
    public int hashCode() {
        return word1.hashCode() ^ word2.hashCode();
    }

    @Override
    public boolean equals(Object obj) {
        return (obj instanceof Bigram) && ((Bigram) obj).word1.equals(word1)
                                       && ((Bigram) obj).word2.equals(word2);
    }
}

这篇关于ArrayList作为HashMap中的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆