Why Java does not allow overriding equals(Object) in an Enum?

前端 未结 5 1491
一整个雨季
一整个雨季 2020-12-03 04:18

I\'ve noticed that the following snippet...

@Override
public boolean equals(Object otherObject) {
    ...
}

...is not allowed for an Enum,

5条回答
  •  离开以前
    2020-12-03 05:14

    Sometimes we need to deal with data that does not conform to Java naming standards. It would be nice to be able to do something like this:

    public enum Channel
    {
        CallCenter("Call Center"),
        BankInternal("Bank Internal"),
        Branch("Branch");
    
        private final String value;
    
        Channel(String value)
        {
            this.value = value;
        }
    
        @Override
        public String toString()
        {
            return value;
        }
    
        public static Channel valueOf(String value)
        {
            for (Channel c : Channel.values())
                if (c.value.equals(value))
                    return c;
            return null;
        }
    
        @Override
        public boolean equals(Object other) 
        {
            if (other instanceof String)
                other = Channel.valueOf((String)other);
            return super.equals(other);
        }
    }
    

    The "String" class would need to be modified to accommodate...

    public boolean equals (Object object) {
        if (object == this) return true;
        if (object instanceof Enum) 
            object = object.toString();
        if (object instanceof String) {
            String s = (String)object;
            // There was a time hole between first read of s.hashCode and second read
            //  if another thread does hashcode computing for incoming string object
            if (count != s.count ||
                (hashCode != 0 && s.hashCode != 0 && hashCode != s.hashCode))
                    return false;
            return regionMatches(0, s, 0, count);
        }
        return false;
    }
    

提交回复
热议问题