Java - Initialize a HashMap of HashMaps

前端 未结 4 1702
小蘑菇
小蘑菇 2020-12-17 15:52

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 Has

4条回答
  •  醉酒成梦
    2020-12-17 16:17

    1. Do not declare your variables with HashMap. It's too limiting.
    2. Yes, you need to initialize class_feature_counts. You'll be adding entries to it, so it has to be a valid map. In fact, initialize both at declaration and not in the constructor since there is only one way for each to start. I hope you're using Java 7 by now; it's simpler this way.

      private Map< String, Integer> classCounts = new HashMap<>();

      private Map< String, Map< String, Integer>> classFeatureCounts = new HashMap<>();

    The compiler will deduce the types from the <>. Also, I changed the variable names to standard Java camel-case style. Are classCounts and classFeatureCounts connected?

提交回复
热议问题