ITPub博客

首页 > IT职业 > IT图书 > java中的枚举类

java中的枚举类

IT图书 作者:usli 时间:2021-09-09 09:50:48 0 删除 编辑

    初识枚举类,我们也许会提出疑问,枚举它是一种新的类型吗?不同于基本数据类型,引用

类型??为了更好地理解,我们从反编译一个enum类开始:

原java代码

import java.util.Arrays;  import java.util.List;    public enum Weather {        Sunny(1, "晴天"), Rainy(2, "雨天"), Cloudy(3, "多云");      private int value;      private String label;        private Weather(int value, String label) {          this.value = value;          this.label = label;      }        public int getValue() {          return value;      }        public String getLabel() {          return label;      }        public static Weather parse(int value) {          Weather result = Weather.Sunny;          switch (value) {          case 1:              result = Weather.Sunny;              break;          case 2:              result = Weather.Rainy;              break;          case 3:              result = Weather.Cloudy;              break;          }          return result;      }        public static List getEnumValues() {          return Arrays.asList(values());      }        public static void main(String[] args) {          System.out.println(Weather.Sunny.getValue() + ":" + Weather.Sunny.getLabel());          Weather weather = Weather.Cloudy;          System.out.println(weather.getValue() + ":" + weather.getLabel());          List list = getEnumValues();          for (Weather sw : list) {              System.out.println(sw.value + "--" + sw.label);          }      }  }

反编译之后:

import java.io.PrintStream; import java.util.*;    public final class Weather extends Enum{            private Weather(String s, int i, int value, String label){          super(s, i);          this.value = value;          this.label = label;      }            public int getValue(){          return value;      }            public String getLabel(){          return label;      }            public static Weather parse(int value){          Weather result = Sunny;          switch(value){              case 1: /*// '

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/3324/viewspace-2813253/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-08-14

  • 博文量
    89
  • 访问量
    808