`
liyixing1
  • 浏览: 965516 次
  • 性别: Icon_minigender_1
  • 来自: 江西上饶
社区版块
存档分类
最新评论

枚举 enum

阅读更多
java的enum其实是一个类。编译器根据你enum的定义会为你生成一个 java.lang.Enum<E>的子类。java.lang.Enum<E>是一个抽象类,定义了很多final方法,也就是说你定义的enum类里不能覆盖它们,你唯一能覆盖的是Object.toString类。同时你定义的enum类是不能被继承的。

先来看看java.lang.Enum类的代码

注意,更具编码规范,枚举值应该全大写(按照常量编写规范)

/*
* %W% %E%
*
* Copyright (c) 2006, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/

package java.lang;

import java.io.Serializable;
import java.io.IOException;
import java.io.InvalidObjectException;
import java.io.ObjectInputStream;
import java.io.ObjectStreamException;

/**
* This is the common base class of all Java language enumeration types.
*
* @author  Josh Bloch
* @author  Neal Gafter
* @version %I%, %G%
* @since   1.5
*/
public abstract class Enum<E extends Enum<E>>
        implements Comparable<E>, Serializable {
    /**
     * The name of this enum constant, as declared in the enum declaration.
     * Most programmers should use the {@link #toString} method rather than
     * accessing this field.
     */
    private final String name;

    /**
     * Returns the name of this enum constant, exactly as declared in its
     * enum declaration.
     *
     * <b>Most programmers should use the {@link #toString} method in
     * preference to this one, as the toString method may return
     * a more user-friendly name.</b>  This method is designed primarily for
     * use in specialized situations where correctness depends on getting the
     * exact name, which will not vary from release to release.
     *
     * @return the name of this enum constant
     */
    public final String name() {
return name;
    }

    /**
     * The ordinal of this enumeration constant (its position
     * in the enum declaration, where the initial constant is assigned
     * an ordinal of zero).
     *
     * Most programmers will have no use for this field.  It is designed
     * for use by sophisticated enum-based data structures, such as
     * {@link java.util.EnumSet} and {@link java.util.EnumMap}.
     */
    private final int ordinal;

    /**
     * Returns the ordinal of this enumeration constant (its position
     * in its enum declaration, where the initial constant is assigned
     * an ordinal of zero).
     *
     * Most programmers will have no use for this method.  It is
     * designed for use by sophisticated enum-based data structures, such
     * as {@link java.util.EnumSet} and {@link java.util.EnumMap}.
     *
     * @return the ordinal of this enumeration constant
     */
    public final int ordinal() {
return ordinal;
    }

    /**
     * Sole constructor.  Programmers cannot invoke this constructor.
     * It is for use by code emitted by the compiler in response to
     * enum type declarations.
     *
     * @param name - The name of this enum constant, which is the identifier
     *               used to declare it.
     * @param ordinal - The ordinal of this enumeration constant (its position
     *         in the enum declaration, where the initial constant is assigned
     *         an ordinal of zero).
     */
    protected Enum(String name, int ordinal) {
this.name = name;
this.ordinal = ordinal;
    }

    /**
     * Returns the name of this enum constant, as contained in the
     * declaration.  This method may be overridden, though it typically
     * isn't necessary or desirable.  An enum type should override this
     * method when a more "programmer-friendly" string form exists.
     *
     * @return the name of this enum constant
     */
    public String toString() {
return name;
    }

    /**
     * Returns true if the specified object is equal to this
     * enum constant.
     *
     * @param other the object to be compared for equality with this object.
     * @return  true if the specified object is equal to this
     *          enum constant.
     */
    public final boolean equals(Object other) {
        return this==other;
    }

    /**
     * Returns a hash code for this enum constant.
     *
     * @return a hash code for this enum constant.
     */
    public final int hashCode() {
        return super.hashCode();
    }

    /**
     * Throws CloneNotSupportedException.  This guarantees that enums
     * are never cloned, which is necessary to preserve their "singleton"
     * status.
     *
     * @return (never returns)
     */
    protected final Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
    }

    /**
     * Compares this enum with the specified object for order.  Returns a
     * negative integer, zero, or a positive integer as this object is less
     * than, equal to, or greater than the specified object.
     *
     * Enum constants are only comparable to other enum constants of the
     * same enum type.  The natural order implemented by this
     * method is the order in which the constants are declared.
     */
    public final int compareTo(E o) {
Enum other = (Enum)o;
Enum self = this;
if (self.getClass() != other.getClass() && // optimization
            self.getDeclaringClass() != other.getDeclaringClass())
    throw new ClassCastException();
return self.ordinal - other.ordinal;
    }

    /**
     * Returns the Class object corresponding to this enum constant's
     * enum type.  Two enum constants e1 and  e2 are of the
     * same enum type if and only if
     *   e1.getDeclaringClass() == e2.getDeclaringClass().
     * (The value returned by this method may differ from the one returned
     * by the {@link Object#getClass} method for enum constants with
     * constant-specific class bodies.)
     *
     * @return the Class object corresponding to this enum constant's
     *     enum type
     */
    public final Class<E> getDeclaringClass() {
Class clazz = getClass();
Class zuper = clazz.getSuperclass();
return (zuper == Enum.class) ? clazz : zuper;
    }

    /**
     * Returns the enum constant of the specified enum type with the
     * specified name.  The name must match exactly an identifier used
     * to declare an enum constant in this type.  (Extraneous whitespace
     * characters are not permitted.)
     *
     * @param enumType the <tt>Class</tt> object of the enum type from which
     *      to return a constant
     * @param name the name of the constant to return
     * @return the enum constant of the specified enum type with the
     *      specified name
     * @throws IllegalArgumentException if the specified enum type has
     *         no constant with the specified name, or the specified
     *         class object does not represent an enum type
     * @throws NullPointerException if <tt>enumType</tt> or <tt>name</tt>
     *         is null
     * @since 1.5
     */
    public static <T extends Enum<T>> T valueOf(Class<T> enumType,
                                                String name) {
        T result = enumType.enumConstantDirectory().get(name);
        if (result != null)
            return result;
        if (name == null)
            throw new NullPointerException("Name is null");
        throw new IllegalArgumentException(
            "No enum const " + enumType +"." + name);
    }

    /**
      * prevent default deserialization
      */
    private void readObject(ObjectInputStream in) throws IOException,
        ClassNotFoundException {
            throw new InvalidObjectException("can't deserialize enum");
    }

    private void readObjectNoData() throws ObjectStreamException {
        throw new InvalidObjectException("can't deserialize enum");
    }

    /**
     * enum classes cannot have finalize methods.
     */
    protected final void finalize() { }
}


如上所示,它本身提供了很多方法。
当然我们写的enum,将会直接从上面的父类继承下这些方法来。

例1

package test;

public enum Enum1 {
ONE, TWO, THREE
}

package test;

public class TestEnum1 {

/**
* 描述:
* @param args
* @author liyixing 2013-12-13 下午4:52:01
*/

public static void main(String[] args) {
for (Enum1 n: Enum1.values()) {
        System.out.println("ordinal: " + n.ordinal()); // enum's int value, start from 0 by default
        System.out.println(n.compareTo(Enum1.TWO));
        System.out.println(n == Enum1.THREE);
        System.out.println(n.name());
        System.out.println(n.getDeclaringClass()); // Number
    }
}

}


在使用枚举时,必须用类型名作前缀,比如Number.ONE,而不能直接用ONE。如果你需要这种便利的话,可以用import static Number.*;来达到目的。

import static test.Enum1.ONE;

System.out.println(Enum1.ONE == ONE); //

另外使用在switch语句中
switch (n) {
case ONE:
break;
case TWO:
break;
default:
break;
}

这里如果写case Enum1.ONE是不允许的。


我们可以往enum里添加属性和方法,构造函数:
需要注意的是,构造函数只能使用private或者不写(默认是private)修饰符

package test;

public enum Enum1 {
ONE, TWO, THREE;

private String name;
public Integer id;

// 默认构造
private Enum1() {

}

// 带参数构造
Enum1(String name) {

}

private void print() {
System.out.println(name);
}

public String say() {
print();
return name;
}
}

分享到:
评论

相关推荐

    三菱FX3G FX3S与四台E700变频器Modbus RTU通讯控制:正反转、频率设定与读取方案,三菱FX3G FX3S与四台E700变频器通讯:Modbus RTU协议实现正反转、频率设定与控制

    三菱FX3G FX3S与四台E700变频器Modbus RTU通讯控制:正反转、频率设定与读取方案,三菱FX3G FX3S与四台E700变频器通讯:Modbus RTU协议实现正反转、频率设定与控制,快速反馈与教程包含,三菱FX3G FX3S 485协议通讯四台三菱E700变频器程序资料 三菱FX3G FX3S+485bd扩展,采用modbus rtu协议,crc校验,通讯控制四台E700变频器,可以实现正反转,停止,频率的设定,频率,电流等的读取。 反馈快,使用方便,包括教程,plc和触摸屏程序,变频器参数设置和接线,别的变频器支持rtu协议也可以实现。 ,三菱FX系列PLC; 485协议通讯; 变频器E700; 通讯控制; 参数设置; 教程。,三菱PLC控制E700变频器:485协议通讯与程序设置全解

    hyphen-nl-0.20050617-10.el7.x64-86.rpm.tar.gz

    1、文件内容:hyphen-nl-0.20050617-10.el7.rpm以及相关依赖 2、文件形式:tar.gz压缩包 3、安装指令: #Step1、解压 tar -zxvf /mnt/data/output/hyphen-nl-0.20050617-10.el7.tar.gz #Step2、进入解压后的目录,执行安装 sudo rpm -ivh *.rpm 4、更多资源/技术支持:公众号禅静编程坊

    西门子S7-1200PLC结构化编程在5轴伺服项目中的应用:模块化设计、触摸屏控制及电气图纸实战解析,西门子S7-1200PLC结构化编程实现多轴联动与多种伺服功能应用:CAD图纸、PLC程序和触摸屏

    西门子S7-1200PLC结构化编程在5轴伺服项目中的应用:模块化设计、触摸屏控制及电气图纸实战解析,西门子S7-1200PLC结构化编程实现多轴联动与多种伺服功能应用:CAD图纸、PLC程序和触摸屏程序协同运作。,西门子S7-1200PLC结构化编程5轴伺服项目 ,包含plc程序、威纶通触摸屏程序、cad电气图纸。 可以实现以下功能,规格有: 1.三轴机械手X轴-Y轴-Z轴联动取放料PTO脉冲定位控制台达B2伺服 2.台达伺服速度模式应用+扭矩模式应用实现收放卷 3.程序为结构化编程,每一功能为模块化设计,功能:自动_手动_单步_暂停后原位置继续运行_轴断电保持_报警功能_气缸运行及报警. 4.每个功能块可以无数次重复调用,可以建成库,用时调出即可 5.上位机采样威纶通触摸屏 6.参考本案例熟悉掌握结构化编程技巧,扩展逻辑思维。 博图14以上都可以打开 ,核心关键词:西门子S7-1200PLC; 结构化编程; 5轴伺服项目; PLC程序; 威纶通触摸屏程序; CAD电气图纸; 三轴机械手; PTO脉冲定位控制; 台达B2伺服; 速度模式应用; 扭矩模式应用; 模块化设计; 轴断电保

    情感分析算法的关键应用领域与典型实战案例

    情感分析算法在多个领域有着广泛的应用场景和丰富的案例

    基于MATLAB仿真的MMC整流站与逆变站柔性互联技术研究:快速工况仿真与环流抑制控制,基于MATLAB仿真的MMC整流站与逆变站运行分析及四端柔性互联工况仿真模拟研究,21电平MMC整流站、MMC逆

    基于MATLAB仿真的MMC整流站与逆变站柔性互联技术研究:快速工况仿真与环流抑制控制,基于MATLAB仿真的MMC整流站与逆变站运行分析及四端柔性互联工况仿真模拟研究,21电平MMC整流站、MMC逆变站、两端柔性互联的MATLAB仿真模型,4端柔性互联、MMC桥臂平均值模型、MMC聚合模型(四端21电平一分钟即能完成2s的工况仿真) 1-全部能正常运行,图四和图五为仿真波形 2-双闭环控制,逆变站PQ控制,整流站站Udc Q控制 3-最近电平逼近调制+子模块电容充电 4-环流抑制控制 ,1. 21电平MMC整流站; 2. MMC逆变站; 3. MATLAB仿真模型; 4. 两端柔性互联; 5. 桥臂平均值模型; 6. 聚合模型; 7. 双闭环控制; 8. 最近电平逼近调制; 9. 子模块电容充电; 10. 环流抑制控制。,基于柔性互联的MMC系统仿真模型:多电平控制与环流抑制研究

    有效应对网络舆情教育培训PPT.pptx

    有效应对网络舆情教育培训PPT.pptx

    高光谱解混和图片去噪 附Matlab代码.rar

    1.版本:matlab2014/2019a/2024a 2.附赠案例数据可直接运行matlab程序。 3.代码特点:参数化编程、参数可方便更改、代码编程思路清晰、注释明细。 4.适用对象:计算机,电子信息工程、数学等专业的大学生课程设计、期末大作业和毕业设计。

    【轴承压力】基于matlab GUI止推轴承压力计算【含Matlab源码 12069期】.zip

    Matlab领域上传的视频是由对应的完整代码运行得来的,完整代码皆可运行,亲测可用,适合小白; 1、从视频里可见完整代码的内容 主函数:main.m; 调用函数:其他m文件;无需运行 运行结果效果图; 2、代码运行版本 Matlab 2019b;若运行有误,根据提示修改;若不会,私信博主; 3、运行操作步骤 步骤一:将所有文件放到Matlab的当前文件夹中; 步骤二:双击打开main.m文件; 步骤三:点击运行,等程序运行完得到结果; 4、仿真咨询 如需其他服务,可私信博主; 4.1 博客或资源的完整代码提供 4.2 期刊或参考文献复现 4.3 Matlab程序定制 4.4 科研合作

    娱乐小工具微信小程序源码下载支持多种流量主.zip

    淘宝买的,直接分享给大家了,没有测试环境,也没有办法去测。但我想,他应该是可以用的

    基于A、RBFS 和爬山算法求解 TSP问题 附Matlab代码.rar

    1.版本:matlab2014/2019a/2024a 2.附赠案例数据可直接运行matlab程序。 3.代码特点:参数化编程、参数可方便更改、代码编程思路清晰、注释明细。 4.适用对象:计算机,电子信息工程、数学等专业的大学生课程设计、期末大作业和毕业设计。

    ACM比赛经验分享(基础知识与算法准备等).zip

    ACM比赛经验分享(基础知识与算法准备等)

    基于matlab平台的芯片字符识别.zip

    运行GUI版本,可二开

    比例-积分-微分 (PID) 鲁棒控制及电流反馈以确保 UPS 的稳定性 附Matlab代码.rar

    1.版本:matlab2014/2019a/2024a 2.附赠案例数据可直接运行matlab程序。 3.代码特点:参数化编程、参数可方便更改、代码编程思路清晰、注释明细。 4.适用对象:计算机,电子信息工程、数学等专业的大学生课程设计、期末大作业和毕业设计。

    机器学习(预测模型):包含恶意网址的数据库或数据集

    该是指包含恶意网址的数据库或数据集,它通常被用于网络安全研究、恶意软件检测、网络欺诈防范等领域。研究人员和安全专家会利用这个数据集来分析恶意网址的特征、行为模式,进而开发出相应的检测算法和防护措施,以识别和阻止恶意网址对用户设备和网络环境造成的潜在威胁。该数据集包含约 651,191 条经过标记的 URL,涵盖了四种主要类型:良性(Benign)、篡改(Defacement)、钓鱼(Phishing)和恶意软件(Malware)。其中,良性 URL 占据了约 428,103 条,篡改 URL 有 96,457 条,钓鱼 URL 为 94,111 条,而恶意软件 URL 则有 32,520 条。该数据集的显著特点是其多类别分类的全面性,不仅包括常见的恶意 URL 类型,还涵盖了大量良性 URL,使得研究人员能够更全面地理解和区分不同类型的 URL。此外,数据集以原始的 URL 形式提供,研究人员可以根据需要提取和创建特征,而不受预设特征的限制。

    集字卡v4.3.4微信公众号原版三种UI+关键字卡控制+支持强制关注.zip

    字卡v4.3.4 原版 三种UI+关键字卡控制+支持获取用户信息+支持强制关注 集卡模块从一开始的版本到助力版本再到现在的新规则版本。 集卡模块难度主要在于 如何控制各种不同的字卡组合 被粉丝集齐的数量。 如果不控制那么一定会出现超过数量的粉丝集到指定的字卡组合,造成奖品不够的混乱,如果大奖价值高的话,超过数量的粉丝集到大奖后,就造成商家的活动费用超支了。我们冥思苦想如何才能限制集到指定字卡组合的粉丝数,后我们想到了和支付宝一样的选一张关键字卡来进行规则设置的方式来进行限制,根据奖品所需的关键字卡数,设定规则就可以控制每种奖品所需字卡组合被粉丝集到的数量,规则可以在活动进行中根据需要进行修改,活动规则灵活度高。新版的集卡规则,在此次政府发布号的活动中经受了考验,集到指定字卡组合的粉丝没有超出规则限制。有了这个规则限制后,您无需盯着活动,建好活动后就无人值守让活动进行就行了,您只需要时不时来看下蹭蹭上涨的活动数据即可。 被封? 无需担心,模块内置有防封功能,支持隐藏主域名,显示炮灰域名,保护活动安全进行。 活动准备? 只需要您有一个认证服务号即可,支持订阅号借用认证服务号来做活动。如果您

    DSP28035的CAN通信升级方案:包括源码、测试固件与C#上位机开发,支持周立功USBCAN-II兼容盒及BootLoader闪烁指示,DSP28035的CAN升级方案及详细配置说明:使用新动力开

    DSP28035的CAN通信升级方案:包括源码、测试固件与C#上位机开发,支持周立功USBCAN-II兼容盒及BootLoader闪烁指示,DSP28035的CAN升级方案及详细配置说明:使用新动力开发板与C#上位机软件实现固件升级,涉及用户代码、BootLoader代码及硬件连接细节,DSP28035的can升级方案 提供源代码,测试用固件。 上位机采用c#开发。 说明 一、介绍 1、测试平台介绍:采用M新动力的DSP28035开发板,CAN口使用GPIO30\31。波特率为500K。 2、28035__APP为测试用的用户代码,ccs10.3.1工程,参考其CMD配置。 3、28035_Bootloader_CAN为bootloader源代码,ccs10.3.1工程; 4、SWJ为上位机,采用VS2013开发,C#语言。 5、测试使用的是周立功的USBCAN-II,can盒,如果用一些国产可以兼容周立功的,则更这里面的ControlCAN.dll即可。 6、升级的app工程需要生成hex去升级,具体参考我给的工程的设置。 7、BootLoader代码,只有D400这一个灯1s闪烁一

    基于Matlab的数字验证码识别系统:预处理与不变矩算法的实践应用及GUI界面构建,基于MATLAB不变矩算法的数字验证码识别系统设计与实现,基于matlab不变矩算法实现数字验证码 过程:先对验证图

    基于Matlab的数字验证码识别系统:预处理与不变矩算法的实践应用及GUI界面构建,基于MATLAB不变矩算法的数字验证码识别系统设计与实现,基于matlab不变矩算法实现数字验证码 过程:先对验证图像进行去噪、定位、归一化等预处理,然后计算待识别数字的不变矩,再进行特征匹配,得到识别结果。 以Matlab软件为开发平台来进行设计实现及仿真,并构建相应的GUI界面。 实验结果表明利用不变矩在识别数字验证码方面具有可行性。 ,关键词:Matlab;不变矩算法;数字验证码;预处理;特征匹配;GUI界面;实验验证;可行性。,Matlab实现数字验证码识别:预处理与不变矩算法的GUI仿真

    基于STM32F103的磁编码器通讯方案:原理图、PCB设计与源码实现,附多摩川协议手册解析,基于STM32F103的精准多摩川绝对值磁编码器通讯解决方案:原理图、PCB设计与源码实践手册,完整包含多

    基于STM32F103的磁编码器通讯方案:原理图、PCB设计与源码实现,附多摩川协议手册解析,基于STM32F103的精准多摩川绝对值磁编码器通讯解决方案:原理图、PCB设计与源码实践手册,完整包含多摩川协议解析,基于STM32F103的多摩川绝对值磁编码器通讯方案 包含:原理图,PCB,源码,多摩川协议手册 ,核心关键词:STM32F103;多摩川绝对值磁编码器;通讯方案;原理图;PCB;源码;多摩川协议手册;,基于STM32F103的绝对值磁编码器通讯方案:原理图PCB与源码解析,附多摩川协议手册

    基于 BP 神经网络特征提取的指纹识别应用 附Matlab代码.rar

    1.版本:matlab2014/2019a/2024a 2.附赠案例数据可直接运行matlab程序。 3.代码特点:参数化编程、参数可方便更改、代码编程思路清晰、注释明细。 4.适用对象:计算机,电子信息工程、数学等专业的大学生课程设计、期末大作业和毕业设计。

    php项目之学生成绩查询系统源码.zip

    php项目之学生成绩查询系统源码,项目仅供学习参考使用

Global site tag (gtag.js) - Google Analytics