java 枚举数组的默认值或初始值
假设我有一个枚举 public enum Day { MONDAY, TUESDAY, ..., SUNDAY }
,然后我实例化一个日期数组 Day[] days = Day[3];
。
如何将某一天(例如 MONDAY
)设为 days
中所有天的默认值?如果按上述方式设置,则 day
的所有元素均为 null。我希望枚举的行为更像整数和字符串,它们分别初始化为 0 和 ""。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
正如其他人所说,枚举是引用类型 - 它们只是特定类的编译器语法糖。 JVM 不了解它们。这意味着该类型的默认值为 null。当然,这不仅仅影响数组 - 这意味着任何类型为枚举的字段的初始值也为 null。
但是,您不必自己循环来填充数组,因为有一个库方法可以提供帮助:
我不知道这对性能有什么好处,但它可以使代码更简单。
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:
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:
Alternatively, you can create a static method in the enum to return an array of the default value:
枚举类的类被初始化为
null
。就像类一样,您需要使用循环在每个位置设置一个值。enum's like classes are initialized to
null
. Just like classes you need to set a value in each position using a loop.Java 默认情况下不会这样做。您必须显式填充数组:
Java won't do this by default. You have to explicitly fill the array:
我知道如何做到这一点的唯一方法是循环遍历数组并将每个设置为 Monday 或 0。
将 Monday = 0 放入枚举中也是一件好事,这样你就知道你会得到什么 int投射它们时的值。
The only way I know how of doing that would be to just loop through the array and set each to Monday or 0.
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.