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.
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).
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.
enum starts always with 0.
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With