I ran into a problem with a section of code that lives within a Java static initializer; I’m not sure that the problem is the static init. Let me step back and frame the problem first. I have a Struts action class that presents a form for collecting date information; said form includes a drop-down menu that is bound to an ArrayList of LabelValueBean objects that contains the months of the year (Jan|1,Feb|2,Mar|3, etc..). The ArrayList of LabelValueBean objects is retrieved from a data provider class using a static method:
Collection months = MyDateProvider.getMonths();
Here’s the pseudo-code inside the date provider class:
public class MyDateProvider {
private static Collection months = new ArrayList();
static {
Calendar c = Calendar.getInstance();
SimpleDateFormat formatter = new SimpleDateFormat("MMM");
SimpleDateFormat monthformatter = new SimpleDateFormat("MM");
for (int i=0; i
The problem is that somehow the ArrayList of LabelValueBean objects contained two instances of March and no February, so the dropdown list would look like this:
January
March
March
April
May
June
July
August
September
October
November
December
Restarting Tomcat temporarily fixed the problem (obviously because MyDateProvider was then reloaded), but my question is how did is it possible for the ArrayList to be missing February and contain two instances of March? Any takers?
Update: the problem has nothing to do with the static init and everything to do with the way I used the Calendar class. The Calendar.getInstance() method returns a Calendar object initialized with the current date and time, so when the web application was restarted on 11/30/2004, the Calendar object reflected that date/time. Looping from 0 to 11 and setting the month (c.set(java.util.Calendar.MONTH, i);
) resulted in the month changing correctly EXCEPT during the month of February , which has only 29 days. The date "02/30/2004" is illegal and so the Calendar class helpfully bumps the month up, which resulted in two instances of March in my drop down. Thanks to Paul Hastings for pointing this out.