枚举类型

枚举enum是一种特殊的类,使用枚举可以很方便的定义常量:


public enum Season {
  SPRING,SUMMER,AUTUMN,WINTER
}
因为是常量,所以一般都是全大写


遍历枚举
for (枚举类类名 变量 : 枚举类类名.values()) {
  System.out.print(变量+"\t");
}
运行结果:
SPRING SUMMER AUTUMN WINTER

枚举类型的运用
public enum Color {
  RED, GREEN, BLANK, YELLOW
}

public class B {


  public static void main(String[] args) {
    System.out.println( Color.RED ) ;
    System.out.println( Color.GREEN ) ;
  }


}

或在switch中的运用

public class HelloWorld {


  public static void main(String[] args) {
    Color c = Color.RED;


    switch (season) {
      case RED :
        System.out.println("红色");
        break;
      case GREEN:
        System.out.println("绿色");
        break;
      case BLANK:
        System.out.println("黑色");
        break;
      case YELLOW:
        System.out.println("黄色");
        break;
    }
  }
}

自定义枚举类

public enum Study05 {


  TANK ("坦克",1),WIZARD ("法师",2),ASSASSIN ("刺客",3),ASSIST ("辅助",4),WARRIOR ("近战",5),RANGED ("远程",6 ),PUSH ("推进",7),FARMING ("打野",8);
  String name ;
  int index;
  //枚举类中的构造方法必须是私有的
  //构造方法的参数类型和数量、顺序必须与枚举类中的常量后小括号内数据类型一致


  private Study05(String name,int index) {
    this.name = name;
    this.index = index;
  }


  public String getName() {
    return name;
  }


  public void setName(String name) {
    this.name = name;
  }


  public int getIndex() {
    return index;
  }


  public void setIndex(int index) {
    this.index = index;
  }

}

调用

public class Study06 {

  public static void main(String[] args) {
    System.out.println(Study05.PUSH.getName());
    System.out.println(Study05.PUSH.getIndex());


    //枚举类的常量
    for (Study05 s : Study05.values()) {
      System.out.println(s+"\t"+"name:"+s.getName()+"\t"+"index:"+s.getIndex());
    }
  }

}

posted @ 2018-08-05 15:56  别念茶茶  阅读(199)  评论(0编辑  收藏  举报