是否可以添加一个ArrayList
作为HashMap
的键。我想保留双字母组的频率计数。二元组是键,值是它的频率。
对于像“he is”这样的每个二元组,我为其创建了一个ArrayList
并将其插入到HashMap
中。但是我没有得到正确的输出。
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
作为 HashMap 中的键,但这是一个非常糟糕的主意,因为它们是可变的。
如果您以任何方式(或其任何元素)更改 ArrayList
,则映射基本上会丢失,因为键不会有相同的 hashCode
就像插入时一样。
经验法则是仅使用不可变数据类型作为 HashMap 中的键。正如 Alex Stybaev 所建议的那样,您可能希望像这样创建一个 Bigram
类:
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);
}
}
关于java - ArrayList 作为 HashMap 中的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9973596/