java 枚举 默认值,java枚举数组的默认值或初始值

川长思鸟来 2022-10-04 12:52 338阅读 0赞

![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]:

发表评论

表情:
评论列表 (有 0 条评论,338人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Java进阶

    枚举进阶 上一节我们讲了[枚举初识][Link 1] 里面主要讲了枚举的实现原理,我们从编译器的角度看了枚举的底层实现以及枚举常用的方法 今天我们看一下枚举添加自定义方