Static import an Array of Calendar objects (cant initialize)

574 Views Asked by At

I need to maintain a number of dates in my program and I'm doing that in the form of an array of Calendar objects.

To access it from several other classes, I plan to declare it in a separate class and import the array as a static import.

Now how can I set values for each of those objects? I'm able to initialize them and access them from the other class like this :

public static Calendar[] cal = new Calendar[]{
                                    Calendar.getInstance(),
                                    Calendar.getInstance()};

Now how do I set values to them?

I tried Calendar.getInstance().set(2012, 11, 10, 16, 30) but i get an error with no suggestions.

So,

  1. Is static import the correct (or best) way to do this?
  2. How do I set values to it?
3

There are 3 best solutions below

1
On BEST ANSWER

The static import part is irrelevant, although frankly it's not terribly nice having a publicly accessible writable field of a mutable array of mutable objects (calendars). A better approach would be to expose an ImmutableList<DateTime> using Guava for ImmutableList and Joda Time for DateTime. (Or possibly LocalDateTime) Anyway...

You could use a static initializer block, but I'd probably just write a method instead:

public static Calendar[] cal = createCalendars();

private static Calendar[] createCalendars() {
    Calendar[] ret = new Calendar[2];
    ret[0] = Calendar.getInstance();
    ret[0].set(2012, 11, 10, 16, 30);
    ret[1] = Calendar.getInstance();
    ret[1].set(...);
    return ret;
}
0
On

This may not suit your taste, but it is admittedly a quite concise way to do it:

public static final Calendar[] cal = createCal(
    2012, 11, 10, 16, 30,
    2012, 11, 11, 16, 30,
    2012, 11, 12, 16, 30
);
static Calendar[] createCal(int... fields) {
  final List<Calendar> cl = new ArrayList<Calendar>();
  for (int i = 0; i < fields.length;) {
    final Calendar c = Calendar.getInstance();
    c.set(fields[i++], fields[i++], fields[i++], fields[i++], fields[i++]);
    cl.add(c);
  }
  return cl.toArray(new Calendar[cl.size()]);
}
0
On

Just FYI, the value of:

Calendar.getInstance().set(2012, 11, 10, 16, 30)

is the value returned by set: void. So you can't initialize

Calendar cal = Calendar.getInstance().set(2012, 11, 10, 16, 30)

See Jon & Marko's more complete answers.