Get seed based on id and date with minimal number of objects
I need to create a seed for shuffling and the seed should be based on an
id (int) and the current date (without the time). This is to preserve the
ordering for an id for a single day and change it the next day. I have got
the following method for this now:
private static long getSeedForShuffle(int id)
{
Date date = new Date();
Calendar cal = MyConstants.UTC_CALENDAR;
cal.setTime(date);
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
double seed = id * 1e8 + year * 1e4 + month * 1e2 + day;
return (long) seed;
}
and this in MyConstants:
public class MyConstants {
public static final Calendar UTC_CALENDAR = Calendar.getInstance(TimeZone
.getTimeZone("UTC"));
}
Is there any way to avoid creating the new date object every time the
method is invoked? i.e. is there something better than doing
Date date = new Date();
in the getSeedForShuffle method, since all this method needs is the
current day, month and year, which can, in principle, be generated only
once daily?
NOTE: This code is running in a web application.
(Started thinking about this after reading Effective Java Item 5: Avoid
creating unnecessary objects.)
No comments:
Post a Comment