Java - Initialize a HashMap of HashMaps

前端 未结 4 1690
小蘑菇
小蘑菇 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:07

    Recursive generic data structures, like maps of maps, while not an outright bad idea, are often indicative of something you could refactor - the inner map often could be a first order object (with named fields or an internal map), rather than simply a map. You'll still have to initialize these inner objects, but it often is a much cleaner, clearer way to develop.

    For instance, if you have a Map> you're often really storing a map of A to Thing, but the way Thing is being stored is coincidentally a map. You'll often find it cleaner and easier to hide the fact that Thing is a map, and instead store a mapping of Map where thing is defined as:

    public class Thing {
        // Map is guaranteed to be initialized if a Thing exists
        private Map data = new Map();
    
        // operations on data, like get and put
        // now can have sanity checks you couldn't enforce when the map was public
    }
    

    Also, look into Guava's Mulitmap/Multiset utilities, they're very useful for cases like this, in particular they do the inner-object initializations automatically. Of note for your case, just about any time you implement Map you really want a Guava Multiset. Cleaner and clearer.

提交回复
热议问题