Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default or initial value for a java enum array

Tags:

java

enums

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 MONDAY) the default value for all Days in days? If set up as above, all the elements of day are null. I want by enum to behave more like ints and Strings, which initialize to 0 and "" respectively.

like image 832
Tanis.7x Avatar asked Jan 11 '11 23:01

Tanis.7x


People also ask

What is the default value for enum in Java?

The default for one who holds a reference to an enum without setting a value would be null (either automatically in case of a class field, or set by the user explicitly).

Do enums have default values?

The default value for an enum is zero. If an enum does not define an item with a value of zero, its default value will be zero.

Do Java enums start at 0 or 1?

enum starts always with 0.

How is enum initialized in Java?

You can't create an instance of Enum using new operators. It should have a private constructor and is normally initialized as: ErrorCodes error = ErrorCodes. BUSSINESS_ERROR. Each constant in the enum has only one reference, which is created when it is first called or referenced in the code.


2 Answers

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.

like image 76
Jon Skeet Avatar answered Oct 16 '22 07:10

Jon Skeet


You can create the array populated with values:

Day[] days = {Day.MONDAY, Day.MONDAY, Day.MONDAY}; 

Alternatively, you can create a static method in the enum to return an array of the default value:

enum Day { MONDAY, TUESDAY, SUNDAY;      public static Day[] arrayOfDefault(int length) {         Day[] result = new Day[length];         Arrays.fill(result, MONDAY);         return result;     } }  Day[] days = Day.arrayOfDefault(3); 
like image 21
Stephen Denne Avatar answered Oct 16 '22 05:10

Stephen Denne