Advantages of Java's enum over the old "Typesafe Enum" pattern? -
in java prior jdk1.5, "typesafe enum" pattern usual way implement type can take finite number of values:
public class suit { private final string name; public static final suit clubs =new suit("clubs"); public static final suit diamonds =new suit("diamonds"); public static final suit hearts =new suit("hearts"); public static final suit spades =new suit("spades"); private suit(string name){ this.name =name; } public string tostring(){ return name; } } (see e.g. item 21 bloch's effective java).
now in jdk1.5+, "official" way use enum:
public enum suit { clubs("clubs"), diamonds("diamonds"), hearts("hearts"), spades("spades"); private final string name; private suit(string name) { this.name = name; } } obviously, syntax bit nicer , more concise (no need explicitly define fields values, suitable tostring() provided), far enum looks typesafe enum pattern.
other differences aware of:
- enums automatically provide
values()method - enums can used in
switch()(and compiler checks don't forget value)
but looks little more syntactic sugar, few limitations thrown in (e.g. enum inherits java.lang.enum, , cannot subclassed).
are there other, more fundamental benefits enum provides not realized typesafe enum pattern?
- "cannot subclassed" isn't restriction. it's 1 of big advantages: ensures there there ever set of values defined in
enum, no more! enumcorrectly handles serialization. can type-safe enums well, it's forgotten (or not known). ensurese1.equals(e2)always impliese1 == e22enumvaluese1,e2(and vice versa, more important).- there specific lightweight data structures handle enums:
enumset,enummap(stolen this answer)
Comments
Post a Comment