Record lost when using date as key for TreeMultimap in Java
I am writing a scheduler where events created are tag to the date. Thus by selecting a date, all events tagged to the date will be shown. I tried doing this with TreeMultimap from google, but I realised not all the records relevant to the date selected are returned. I am wondering is there any known issue using date as the key for TreeMultimap or is purely problem of my code.
TreeMultimap<Date, EventInstance> dateToEventMultimap = TreeMultimap.create();
// Build multimap.
Calendar cal1 = GregorianCalendar.getInstance();
Calendar cal2 =开发者_StackOverflow中文版 GregorianCalendar.getInstance();
cal1.clear(); // Clears the values of all the time fields.
cal2.clear();
for (EventInstance eventInstance : myEventList) {
cal1.setTime(eventInstance.getTimeDate());
cal2.set(cal1.get(Calendar.YEAR),
cal1.get(Calendar.MONTH),
cal1.get(Calendar.DAY_OF_MONTH));
dateToEventMultimap.put(cal2.getTime(), eventInstance);
}
If a mutable object is used as a key and it gets modified, the record will no longer be found, as the hash will be different. It will remain in the old hash "bin", but the hash map implementation will search it in a "bin" based on the new hash key, and it won't be there (unless by pure chance, which is rather small for good hash code implementation).
精彩评论