Dav*_*ams 13 java oop initialization
我是java的新手,通过创建一个简单的NaiveBayes分类器来练习.我仍然是对象实例化的新手,并想知道如何初始化HashMaps的HashMap.在将新观察值插入分类器时,我可以为给定类中的未见特征名创建新的HashMap,但是我是否需要初始化?
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
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,这个问题并不是针对Naive Bayes分类器的,因为我想提供一些上下文.
Bob*_*der 20
是的,您需要初始化它.
class_feature_counts = new HashMap<String, HashMap<String, Integer>>();
Run Code Online (Sandbox Code Playgroud)
如果要向class_feature_counts添加值,还需要实例化它:
HashMap<String, Integer> val = new HashMap<String, Integer>();
// Do what you want to do with val
class_feature_counts.put("myKey", val);
Run Code Online (Sandbox Code Playgroud)
dim*_*414 11
递归的通用数据结构,如地图的地图,虽然不是一个彻头彻尾的坏主意,但通常表示你可以重构的东西 - 内部地图通常可以是一阶对象(它包含地图),而不仅仅是地图.您仍然需要初始化这些内部对象,但它通常是一种更清晰,更清晰的开发方式.
例如,如果你有一个Map<A,Map<B,C>>你经常真正存储A到Thing的地图,但Thing的存储方式恰好是一张地图.你经常会发现它更清晰,更容易隐藏Thing是一个地图的事实,而是存储一个Map<A,Thing>定义为:
public class Thing {
// Map is guaranteed to be initialized if a Thing exists
private Map<B,C> data = new Map<B,C>();
// operations on data, like get and put
// now can have sanity checks you couldn't enforce when the map was public
}
Run Code Online (Sandbox Code Playgroud)
另外,看看Guava的Mulitmap/Multiset实用程序,它们对于这样的情况非常有用,特别是它们自动执行内部对象初始化.对于你的情况,几乎在你实现的任何时候Map<E, Integer>你真的想要一个Guava Multiset.更清洁,更清晰.