|
-
June 16th, 2005, 10:00 AM
#1
HashMap replaces pair key/value, why?
I am having this problem with a HashMap: when trying to insert a new Long value using a Date as the key, my first or second pair key/value entry gets replaced with the third one even though the key is different.
Code:
for (Iterator iter = psr.getProduction().iterator(); iter.hasNext();)
{
Object[] current = (Object[]) iter.next();
Date date = new Date();
date.setTime(((Date)current[0]).getTime());
log.info("Production=> date: " + date );
objectCal.setTime(date);
Long qte = (Long) current[1];
if(date.compareTo(today) < 0 )
{
log.info("Production: " + qte + " skipped");
continue;
}
log.info("Production=> objectDate: " + objectCal.getTime() + ", Qte: " + qte );
log.info("Production=> today: " + today );
// If the map already contains the key, add up results.
if( entries.containsKey( date ))
{
Long initial = (Long)entries.get( date );
Long sum = new Long( qte.longValue() + initial.longValue() );
entries.remove( date );
entries.put( date, sum );
}
else
entries.put( date, qte );
log.info("Production: " + qte + " added");
}
getProduction() is a List. In my problem, it only contains 3 items
i.e.
on the first loop, I pass a date, say "Tue Jun 14 00:00:00 EDT 2005" as the key and 45 as a Long value. It is placed in HashMap slot[6] (I can see in the debugger representation of the HashMap)
In the second loop, I pass the date as 'Wed Jun 15 00:00:00 EDT 2005' with the Long value of 5. It is placed in HashMap slot[2]
In the third loop, I pass the date as 'Thu Jun 16 00:00:00 EDT 2005' and a value of 5. It is placed in HashMap slot[6].
The code only runs through the
entries.put( date, qte ) portion in this example.
The result is that the third entry totally replaces the first one in the HashMap and I lose the first pair key/value. The indicated size of the HahMap is 2, I can only see the last 2 keys entered even though I only used different keys.
I tried to use a Hashtable instead of a HashMap, but I get the same problem. I also tried to use date.toString() as a key, same results with different indexes in the HashMap
Why is that happening? How can I go aroiund it. I need to sorted on the keys later as I am adding to the HashMap from different Lists that may not be in the same date order.
Last edited by lsmeteor; June 16th, 2005 at 10:21 AM.
Cheers,
Laurent
For an aviator, the three best things in life are a good landing, a good orgasm, and a good sh*t. A night carrier landing is one of the few opportunities to experience all three at the same time.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|