I am just wondering what would be the correct method of making the code below immutable.
Date d = new Date();
Scheduler.scheduleTask(task1, d);
d.setTime(d.getTime() + ONE_DAY);
Scheduler.scheduleTask(task2, d);
I am just wondering what would be the correct method of making the code below immutable.
Date d = new Date();
Scheduler.scheduleTask(task1, d);
d.setTime(d.getTime() + ONE_DAY);
Scheduler.scheduleTask(task2, d);
You can't make that immutable. Immutability is a property of an object. It says that, once instantiated, an object's internal state does not change.
The java.util.Date
class, for whatever reason, was not designed to be immutable. This is illustrated nicely by the ability to change the value it contains:
d.setTime(d.getTime() + ONE_DAY);
If you wanted to change your code so that it was not mutating this object, you could do something like:
Date firstDate = new Date();
Scheduler.scheduleTask(task1, firstDate);
Date secondDate = new Date(firstDate.getTime() + ONE_DAY);
Scheduler.scheduleTask(task2, secondDate);
If you can avoid it, do not use java.util.Date
. There was a new Date/Time API added in Java 8 located in java.time
. The classes located in there are immutable and are often better choices.
Date object implements clone method, so you can clone your date (d) object instead of making references. In your example would be like this:
Date d = new Date();
Scheduler.scheduleTask(task1, (Date) d.clone());
d.setTime(d.getTime() + ONE_DAY);
Scheduler.scheduleTask(task2, (Date) d.clone());