• JVM中的枚举


    【问题】

      写代码过程中,定义了一组枚举WEEKDAYS[MONDAY,TUESDAY,......]。此时,如果输入参数为一个WEEKDAYS的参数,我们对这个参数进行值判定的时候,到底用eaquals还是==去判断呢?在JVM中,枚举到底是如何存放的?<Effective Java>中说枚举是单例模式的最佳实现方式,为什么?

    【查阅资料】

      使用javac将代码进行编译,并用javap命令查看编译之后的字节码文件:

      可以看到,枚举类经过编译器的处理,拥有以下特点:

    1. 构造函数私有;
    2. 类为final类,继承了java.lang.Enum<E>
    3. 定义了values()方法返回所有的枚举实例;
    4. valueOf可以根据枚举的字符串形式转为枚举类实例;

      这里,我们可以再看看java.lang.Enum<E>的实现:

    public abstract class Enum<E extends Enum<E>>
            implements Comparable<E>, Serializable {
    
        private final String name;
        public final String name() {
            return name;
        }
    
        private final int ordinal;
        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;
        }
    
        public String toString() {
            return name;
        }
        public final boolean equals(Object other) {
            return this==other;
        }
    
        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();
        }
    
        public final int compareTo(E o) {
            Enum<?> other = (Enum<?>)o;
            Enum<E> 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
         */
        @SuppressWarnings("unchecked")
        public final Class<E> getDeclaringClass() {
            Class<?> clazz = getClass();
            Class<?> zuper = clazz.getSuperclass();
            return (zuper == Enum.class) ? (Class<E>)clazz : (Class<E>)zuper;
        }
    
        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 constant " + enumType.getCanonicalName() + "." + name);
        }
    
        /**
         * enum classes cannot have finalize methods.
         */
        protected final void finalize() { }
    
        /**
         * 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");
        }
    }

      对于枚举类型来说,equals与==是一样的。而name()和toString()也是一样的,都是返回枚举内部的name字段。为了保护这种单例形态,枚举不能进行clone()。所以,在使用枚举时,拿到枚举实例再进行A.toString().equals(B.toString())的比较是完全没有必要的,直接A==B来判断就好,因为枚举的定义就是static final的,只有一份且值也无法被修改。

    【参考】

    https://www.cnblogs.com/alter888/p/9163612.html

  • 相关阅读:
    一卦,测一年运气
    测一下我心中想的事
    一卦,测一下我心里想的事
    这一卦,学到了不少东西
    癸山丁向下卦(七运)
    起卦测我心里想的事
    现在的卦,越来越看不懂了
    luogu P2759 奇怪的函数 |二分答案
    luogu P2515 [HAOI2010]软件安装 |Tarjan+树上背包
    luogu P2343 宝石管理系统 |分块+堆
  • 原文地址:https://www.cnblogs.com/bruceChan0018/p/15086311.html
Copyright © 2020-2023  润新知