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!
  • enum correctly handles serialization. can type-safe enums well, it's forgotten (or not known). ensures e1.equals(e2) always implies e1 == e2 2 enum values e1 , e2 (and vice versa, more important).
  • there specific lightweight data structures handle enums: enumset , enummap (stolen this answer)

Comments

Popular posts from this blog

linux - Mailx and Gmail nss config dir -

c# - Is it possible to remove an existing registration from Autofac container builder? -

php - Mysql PK and FK char(36) vs int(10) -