I want to have one DateWrapper - representing a date (built for Hibernate persistance, but this is another story) - at most existing at the same time for the same date.
I'm a bit confused about collisions and good keys for hashing. I'm writing a factory for a DateWrapper
object, and I thought to use the milliseconds of the parsed date as the key as I've seen others doing. But, what happens if there is a collision?. Milliseconds are always different from one another, but the internal table may be smaller than the Long that could exist. And once the hash map has a collision, it uses the equals, but how can it distinguish two different object from my Long? Maybe, it's the put method to drop (overwrite) some value I'd like to insert...
So, is this code safe, or is it bugged??
package myproject.test;
import java.util.HashMap;
import java.util.Map;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import myproject.utilities.DateWrapper;
public class DateWrapperFactory {
static Map <Long, DateWrapper> cache = new HashMap<Long, DateWrapper>();
static DateTimeFormatter parser =
DateTimeFormat.forPattern("yyyy-MM-dd");
static DateWrapperFactory instance = new DateWrapperFactory();
private DateWrapperFactory() {
}
public static DateWrapperFactory getInstance() {
return instance;
}
public static DateWrapper get(String source) {
DateTime d = parser.parseDateTime(source);
DateWrapper dw = cache.get(d.getMillis());
if (dw != null) {
return dw;
} else {
dw = new DateWrapper(d);
cache.put(d.getMillis(), dw);
return dw;
}
}
}
package myproject.test;
import org.joda.time.DateTime;
public class DateWrapper {
private DateTime date;
public DateWrapper(DateTime dt) {
this.date = dt;
}
}