开发者社区> 问答> 正文

如何返回枚举数组,出现此错误

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

问题来源:Stack Overflow

展开
收起
montos 2020-03-22 15:21:01 623 0
1 条回答
写回答
取消 提交回答
  • 该方法是由编译器隐式定义的,因此,如果尝试再次将此方法声明到枚举中,则会出现编译错误,例如 "The enum .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]
    
    

    回答来源:Stack Overflow

    2020-03-22 15:23:02
    赞同 展开评论 打赏
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载