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

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

问题描述

是否可以添加一个ArrayList作为HashMap的key.我想保留二元组的频率计数.二元组是键,值是它的频率.

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.

对于像he is"这样的每个二元组,我为它创建了一个 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天全站免登陆