Andre's Blog

20160907 Benefits Of Java Enumerations Compared To C++

[JAVA] [JAVA.LANG.ENUM]

The last days I was using java.lang.Enum a lot and I really must say : I AM SO HAPPY ABOUT IT!

I was coding C++ for years and it happens quite often you need the string representation of an enumeration value or you have to find the enumeration value corresponding to a string. In C++ you have to maintain both, the enumeration, which you can use in switch-case-statements and the functions computing one into the other.

You can end up in a worst-case-scenario if you decide to do everything with strings, because then your compiler is not able to find your typos.

In Java you declare your enumeration, e.g.

Enum Colors {
    red,
    green,
    blue
};

and when you need the string representation you just

String red = Colors.red.name();

and when you need the enumeration value you just

String red = "red";
Colors value = Colors.valueOf(red);

Nice!

Select where to go ...


The Blog
My Technical Blogs
Projects
Blogs Of Friends
RSS
CV/About
Me