java - 如何返回一个枚举数组,得到这个错误
问题描述
public enum colors{
Green,
YELLOW,
RED,
ERROR;
public static colors[] values(){
/*
Returns an array containing the constants of this enum type, in the order they are declared.
*/
colors[] c = {GREEN,YELLOW,RED,ERROR};
return c;
}
}
得到错误: values() 已经用颜色定义了
解决方案
这个方法是由编译器隐式定义的,所以如果你试图在你的枚举中再次声明这个方法,你会得到像这样的编译错误"The enum <class-name>.colors already defines the method values() implicitly"
您可以在此处查看文档,https://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.9.2
请注意上述文档中的这一行,
“由此可见,枚举类型声明不能包含与枚举常量冲突的字段,也不能包含与自动生成的方法(values() 和 valueOf(String))冲突的方法或覆盖 Enum 中最终方法的方法(equals( Object)、hashCode()、clone()、compareTo(Object)、name()、ordinal() 和 getDeclaringClass())。"
这里,E 是枚举类型的名称,那么该类型具有以下隐式声明的静态方法。
/**
* Returns an array containing the constants of this enum
* type, in the order they're declared. This method may be
* used to iterate over the constants as follows:
*
* for(E c : E.values())
* System.out.println(c);
*
* @return an array containing the constants of this enum
* type, in the order they're declared
*/
public static E[] values();
因此,您不需要再次声明它,而是可以通过简单地调用来获取数组colors.values()
。
有关示例,请参阅以下简单代码片段:
public class Test {
public static void main(String[] args) {
colors[] values = colors.values();
System.out.println(Arrays.toString(values));
}
public enum colors {
Green,
YELLOW,
RED,
ERROR;
}
}
输出:
[Green, YELLOW, RED, ERROR]
推荐阅读
- get - 为什么我在执行 get API 时收到 promise denied 错误
- php - 转换失败!联系服务器管理员。使用 OfficeConverter 时出错
- julia - “writecsv()”在 JuliaPro 1.5.0 中如何工作?
- fiware - 我们可以使用关系来交叉引用不同服务路径中的实体吗?
- ms-access - 如何使命令按钮集合 ms 访问
- wordpress - 我的主题不显示预览以及如何将我的主题设置为帖子编辑器和页面编辑器?- 从头开始的wordpress主题
- python - 无法将 bool 转换为 numpy.ndarray
- python-3.x - 如何使 pyinstaller 在 CentOS 7 上与 rh-python38-python-devel 一起工作?
- nginx - NGINX Ingress 不转发
- scala - 从另一个类访问火花