Search code examples
javatreemap

Putting into TreeMap - strange behavior


I would by grateful for any advice. I have this code:

TreeMap<Date, Double> predictPoints = new TreeMap<Date, Double>();
while(iterator_time.hasNext()) {
            Date time = iterator_time.next();

            if (count < obs.toList().size()) {
                count++;tmp1++;
                continue;
            } else {            
                for (int j = 0; j <= degreePolynom; j++) {
                    predictConsumption += coeff[j] * Math.pow(time.getTime(), j);
                }
                predictPoints.put(time, predictConsumption);
                predictConsumption = 0.0;
                count++;tmp2++;
            }

        }

I iterate through Vector and in this vector is 35036 number. tmp1 and tmp2 variables are just for check. 80% of data are skipped (if block, obs.toList().size() is 35036) and the rest of data (20%) I use. Problem: I iterate in else block 7007 times but in predictPoints is only 7003 items. This problem does not occur if I use less data. If I use TreeMap without Date, for example TreeMap<Integer, Double> then I have 7007 items in map and it is right. Every number is unique - I tested it. Where are 4 lost items? :-(

Thanks for any advice.


Solution

  • Maps don't support duplicate keys, so if you add 7007 items to a map, but only end up with 7003 items, then 4 of the items had duplicate key and replaced the previous value.

    Check the return value of put() to check if it replaced an existing value.