Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/384.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何返回枚举数组,获取此错误_Java_Arrays_Enums_Compiler Errors - Fatal编程技术网

Java 如何返回枚举数组,获取此错误

Java 如何返回枚举数组,获取此错误,java,arrays,enums,compiler-errors,Java,Arrays,Enums,Compiler Errors,获取错误:values()已在colors中定义。此方法是由编译器隐式定义的,因此,如果您尝试再次在枚举中声明此方法,您将得到编译错误,如“enum.colors已隐式定义方法值” 您可以在这里查看文档 在上述文件中注意这一行 因此,枚举类型声明不能包含与枚举常量冲突的字段,也不能包含与自动生成的方法(values()和valueOf(String))冲突的方法,也不能包含重写枚举中最终方法(equals(Object)、hashCode()、clone()、compareTo(Object)、

获取错误:values()已在colors中定义。此方法是由编译器隐式定义的,因此,如果您尝试再次在枚举中声明此方法,您将得到编译错误,如“enum.colors已隐式定义方法值”

您可以在这里查看文档

在上述文件中注意这一行

因此,枚举类型声明不能包含与枚举常量冲突的字段,也不能包含与自动生成的方法(values()和valueOf(String))冲突的方法,也不能包含重写枚举中最终方法(equals(Object)、hashCode()、clone()、compareTo(Object)、name()和ordinal()的方法,和getDeclaringClass()

这里,E是枚举类型的名称,那么该类型具有以下隐式声明的静态方法

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;
   }
}
因此,您不需要再次声明它,只需调用
colors.values()
即可获得数组

有关示例,请参阅下面的简单代码段:

/**
* 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();
输出:

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;
    }   
}
请检查一下电话号码


编译器在创建枚举时会自动添加一些特殊方法。例如,它们有一个静态值方法,该方法返回一个数组,该数组按声明的顺序包含枚举的所有值。此方法通常与for each构造结合使用,以迭代枚举类型的值。例如,下面行星类示例中的此代码迭代太阳系中的所有行星。

java中的枚举将有一个生成的静态方法
values()
,并且它不能被重写,如中所述。

错误消息会准确地告诉您错误所在。您不需要实现自己的值方法。除此之外,
Green
!=<代码>绿色。另外,ERROR是我最喜欢的颜色。Java已经提供了您试图实现的确切的
values()
方法。如果必须,您可以自由地(重新)为自己编写类似的方法,但不能调用它
values()
[Green, YELLOW, RED, ERROR]