开发者

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


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);


enum's like classes are initialized to null. Just like classes you need to set a value in each position using a loop.


Java won't do this by default. You have to explicitly fill the array:

final Day DEFAULT_DAY = Day.MONDAY;
Day[] days = Day[3];
for (int i = 0; i<days.length; i++)
{
    days[i] = DEFAULT_DAY;
}


The only way I know how of doing that would be to just loop through the array and set each to Monday or 0.

for (int i = 0; i < days.length; i++)
{
day[i] = Days.Monday
}

And its also a good thing to put Monday = 0 in your enum so you know what int you'll get out of the values when you cast them.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜