首页 > 解决方案 > 如何返回一个枚举数组,得到这个错误

问题描述

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() 已经用颜色定义了

标签: javaarraysenumscompiler-errors

解决方案


这个方法是由编译器隐式定义的,所以如果你试图在你的枚举中再次声明这个方法,你会得到像这样的编译错误"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]

推荐阅读