java 枚举 默认值,java枚举数组的默认值或初始值
![Image 1][]
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.
解决方案
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.
[Image 1]:
还没有评论,来说两句吧...