Tanis.7x Tanis.7x - 1 year ago 131
Java Question

Default or initial value for a java enum array

Say I have an enum

public enum Day { MONDAY, TUESDAY, ..., SUNDAY }
, then I instantiate a day array
Day[] days = Day[3];

How do I make a day (eg
) the default value for all Days in
? If set up as above, all the elements of
are null. I want by enum to behave more like ints and Strings, which initialize to 0 and "" respectively.

Answer Source

As others have said, enums are reference types - they're just compiler syntactic sugar for specific classes. The JVM has no knowledge of them. That means the default value for the type is null. This doesn't just affect arrays, of course - it means the initial value of any field whose type is an enum is also null.

However, you don't have to loop round yourself to fill the array, as there's a library method to help:

Day[] days = new Day[3];
Arrays.fill(days, Day.MONDAY);

I don't know that there's any performance benefit to this, but it makes for simpler code.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download