title: Layered HashMap Nth Order HMM implementation
body: <p>I have implemented 1st, 2nd and 3rd order Hidden Markov Models using HashMaps as opposed to a transition matrix. I use these HMMs to count the number of occurrences of musical notes (modeled as integers 0-128) after 1 note/ 2 notes/ 3 notes, depending on the order.</p>
  
  <p>For example the implementation for the 2nd order is:</p>
  
  <pre><code>public void updateWeigths(ArrayList&lt;Note&gt; notes, HashMap&lt;Integer, HashMap&lt;Integer, HashMap&lt;Integer, Double&gt;&gt;&gt; hm) {
      for (int i=0; i&lt;notes.size()-2; i++) {
          int prevPitch1 = notes.get(i).getPitch();
          int prevPitch2 = notes.get(i+1).getPitch();
          int nextPitch = notes.get(i+2).getPitch();
          if (prevPitch1 &gt; 0 &amp;&amp; prevPitch2 &gt; 0 &amp;&amp; nextPitch &gt; 0) {
              if (hm.containsKey(prevPitch1)) {
                  HashMap&lt;Integer, HashMap&lt;Integer, Double&gt;&gt; nextMapping1 = hm.get(prevPitch1);
                  if (nextMapping1.containsKey(prevPitch2)){
                      HashMap&lt;Integer, Double&gt; nextMapping2 = nextMapping1.get(prevPitch2);
                      if (nextMapping2.containsKey(nextPitch)) {
                          double prob = nextMapping2.get(nextPitch);
                          nextMapping2.put(nextPitch, prob+1);
                      }
                      else {
                          nextMapping2.put(nextPitch, 1.0);
                      }
                  }
                  else {
                      nextMapping1.put(prevPitch2, new HashMap&lt;Integer, Double&gt;());
                  }
              }
              else {
                  hm.put(prevPitch1, new HashMap&lt;Integer,HashMap&lt;Integer,Double&gt;&gt;());
              }
          }
      }
  }
  </code></pre>
  
  <p>I want to implement an arbitrary order HMM using the same pattern. I tried using polymorphism but I get ClassCastException each time. Not entirely sure how to use Generics on this. The trick I guess is to know when you're on the last HashMap so you can update the count Double value.</p>
  
  <p>Any suggestions would be great!</p>