Java - 初始化 HashMap 的 HashMap
我是 Java 新手,我通过创建一个简单的 NaiveBayes 分类器来练习.我还是对象实例化的新手,想知道如何初始化 HashMap 的 HashMap.在向分类器中插入新的观察值时,我可以为给定类中未见过的特征名称创建一个新的 HashMap,但我需要初始化吗?
I am new to java and practicing by creating a simplistic NaiveBayes classifier. I am still new to object instantiation, and wonder what to do to initialize a HashMap of HashMaps. When inserting new observations into the classifier, I can create a new HashMap for an unseen feature name in a given class, but do I need to initialize?
import java.util.HashMap;
public class NaiveBayes {
private HashMap<String, Integer> class_counts;
private HashMap<String, HashMap<String, Integer>> class_feature_counts;
public NaiveBayes() {
class_counts = new HashMap<String, Integer>();
// do I need to initialize class_feature_counts?
}
public void insert() {
// todo
// I think I can create new hashmaps on the fly here for class_feature_counts
}
public String classify() {
// stub
return "";
}
// Naive Scoring:
// p( c | f_1, ... f_n) =~ p(c) * p(f_1|c) ... * p(f_n|c)
private double get_score(String category, HashMap features) {
// stub
return 0.0;
}
public static void main(String[] args) {
NaiveBayes bayes = new NaiveBayes();
// todo
}
}
请注意,此问题并非特定于朴素贝叶斯分类器,只是想我会提供一些上下文.
Note this question is not specific to Naive Bayes classifiers, just thought I would provide some context.
推荐答案
是的,你需要初始化它.
Yes, you need to initialize it.
class_feature_counts = new HashMap<String, HashMap<String, Integer>>();
当你想给 class_feature_counts 添加一个值时,你也需要实例化它:
When you want to add a value to class_feature_counts, you need to instantiate it too:
HashMap<String, Integer> val = new HashMap<String, Integer>();
// Do what you want to do with val
class_feature_counts.put("myKey", val);
相关文章