开发者

What is the drawback of having more instances of enum type other than in the enum declaration?

It is a compile-time error to attempt to explicitly instantiate an enum type

(§15.9.1). The final clone method in Enum ensures that enum constants can never be cloned, and the special treatment by the serialization mechanism ensures that duplicate instances are never created as a result of deserialization.开发者_如何学Python Reflective instantiation of enum types is prohibited. Together, these four things ensure that no instances of an enum type exist beyond those defined by the enum constants.

What is the drawback of having more instances of enum type other than in the enum declaration?


The drawback is that you're throwing away the statically checkability of enums.

You can statically ensure that a switch on an enum value does indeed handle all cases. You can statically ensure that calling a method with an enum does a sane thing. You can statically ensure that there's a translation of every enum value in your resource bundles. And many more things.

You can make sure that equals() is equivalent to == with enums.

All of this defines an enum.

If you want something "similar" to an enum, then write it: it's not too hard.


It would break comparisons. You want

if (myEnumValue == yourEnumValue)
{
}

to work, if there could be multiple instances of the same enum value, there's no guarantee that reference-based testing like this would work. Compare with strings.


Well, I guess it would cause confusion, because people expect to be able to compare against enums using ==. Being able to clone would break the semantics.


If you had two enums then the following instruction could be true or false...

public boolean isEnumBlack(EnumType enum) {
    if (enum == EnumType.BLACK) {
        return true;
    } else {
        return false;
    }
}

Then if you called this method with an "instance" of the EnumType, BLACK... then it would not return true.

isEnumBlack(BLACK) would return false, even though according to the code it should be returning true. Enum's would no longer be enum's!


In addition to all of the other good answers, it would break EnumSet. EnumSet is implemented, depending on the size of the enum, as a single long or an array of longs, where each bit represents the inclusion or exclusion of one particular enum value. If the number and order of enums were not constant, this would not work.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜