java 枚举中的结构问题

public class test {
    static int install_update=0;
    static int framework_install=0;
    static int framework_install_recovery=0;

    static int uninstall=0;
    static int framework_uninstall_recovery=0;

    public static void main(String [] args){
          System.out.println("hello word");
          final int TYPE_COUNT = Type.values().length;
          System.out.println(TYPE_COUNT);
      }
    public enum Type {
        INSTALLER( install_update, framework_install,framework_install_recovery),
        UNINSTALLER( uninstall, uninstall,  framework_uninstall_recovery);
        public final int title;
        public final int text_flash;
        public final int text_flash_recovery;

        Type( int title,  int text_flash,  int text_flash_recovery) {
            this.title = title;
            this.text_flash = text_flash;
            this.text_flash_recovery = text_flash_recovery;
        }
    }

    }

请问这里的
INSTALLER( install_update, framework_install,framework_install_recovery),

    UNINSTALLER( uninstall, uninstall,  framework_uninstall_recovery);
    
    这是“INSTALLER“ “UNINSTALLER”里面什么数据结构呢?

阅读 1.7k
2 个回答

枚举比较神奇,每个枚举项都是当前枚举类的实例
看你的代码,分下段:

public enum Type {
        // 枚举项
        INSTALLER( install_update, framework_install,framework_install_recovery),
        UNINSTALLER( uninstall, uninstall,  framework_uninstall_recovery);
        // 类属性
        public final int title;
        public final int text_flash;
        public final int text_flash_recovery;
        // 构造方法
        Type( int title,  int text_flash,  int text_flash_recovery) {
            this.title = title;
            this.text_flash = text_flash;
            this.text_flash_recovery = text_flash_recovery;
        }
    }

我们把这个枚举类改造一下,不使用enum关键字,使用class:

这个类只是简单模拟枚举类
public final class Type extends Enum<Type> {
    public final int title;
    public final int text_flash;
    public final int text_flash_recovery;
    // 构造方法
    Type( int title,  int text_flash,  int text_flash_recovery) {
        this.title = title;
        this.text_flash = text_flash;
        this.text_flash_recovery = text_flash_recovery;
    }
}

这就是一个普普通通的类,枚举项什么意思呢,再看:

public final class Type extends Enum<Type> {
    public static Type INSTALLER = new Type(install_update, framework_install, framework_install_recovery);
    
    public static Type UNINSTALLER = new Type(uninstall, uninstall, framework_uninstall_recovery);

    public final int title;
    public final int text_flash;
    public final int text_flash_recovery;
    // 构造方法
    Type( int title,  int text_flash,  int text_flash_recovery) {
        this.title = title;
        this.text_flash = text_flash;
        this.text_flash_recovery = text_flash_recovery;
    }
}

这样简单改造,就可以很清晰了。

java 里 enum 是类,emuerator 是这个类的对象。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题