hashCode と equals は同じフィールドを使用する必要があり、これらのフィールドは事実上不変でなければなりません (つまり、ハッシュされたコレクションに追加した後は変更されません)。
これには、日付または任意のフィールドを含めることができます。
ところで、不変にすることができ、わずかに高速であるため、long
代わりに使用することを好みます。Date
タイムスタンプを ID として使用する場合は、ミリ秒 (またはタイムスタンプを保存できる場合はマイクロ秒) を押し上げることで一意であることを確認することもできます。
private static final AtomicLong TIME_STAMP = new AtomicLong();
// can have up to 1000 ids per second.
public static long getUniqueMillis() {
long now = System.currentTimeMillis();
while (true) {
long last = TIME_STAMP.get();
if (now <= last)
now = last + 1;
if (TIME_STAMP.compareAndSet(last, now))
return now;
}
}
また
private static final AtomicLong TIME_STAMP = new AtomicLong();
// can have up to 1000000 ids per second.
public static long getUniqueMicros() {
long now = System.currentTimeMillis() * 1000;
while (true) {
long last = TIME_STAMP.get();
if (now <= last)
now = last + 1;
if (TIME_STAMP.compareAndSet(last, now))
return now;
}
}