java枚举数组的默认值或初始值 [英] Default or initial value for a java enum array

查看:2277
本文介绍了java枚举数组的默认值或初始值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个枚举 public enum Day {MONDAY,TUESDAY,...,SUNDAY} ,然后我实例化一个日阵列 Day [ ] days = Day [3];



我如何做一天(例如 MONDAY days 中的所有天数的默认值?如果设置如上, day 的所有元素都为空。我想通过枚举来表现更像int和strings,它们分别初始化为0和。

解决方案

正如其他人所说,枚举是引用类型 - 它们只是针对特定类的编译器语法糖。 JVM不了解它们。这意味着该类型的默认值为null。这不只是影响数组,当然这意味着其类型为枚举的任何字段的初始值也为空。



但是,您没有循环自己来填充数组,因为有一个库方法来帮助:

  Day [] days = new Day [3 ]。 
Arrays.fill(days,Day.MONDAY);

我不知道有这样的表现有好处,但是它使代码更简单。


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.

这篇关于java枚举数组的默认值或初始值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆