日付を表す1つのDateWrapperが必要です(Hibernateの永続性のために構築されていますが、これは別の話です)-せいぜい同じ日付で同時に存在します。
衝突とハッシュの適切なキーについて少し混乱しています。私はDateWrapper
オブジェクトのファクトリを書いています。他の人が行っているのを見たように、解析された日付のミリ秒をキーとして使用することを考えました。しかし、もし衝突したらどうなるでしょうか?. ミリ秒は常に互いに異なりますが、内部テーブルは存在する可能性のある Long よりも小さい場合があります。ハッシュ マップに衝突が発生すると、equals が使用されますが、Long から 2 つの異なるオブジェクトをどのように区別できるでしょうか? たぶん、挿入したい値を削除(上書き)するのはputメソッドです...では、このコードは安全ですか、それともバグですか??
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;
}
}