Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: enum values() and valueOf(String)

Tags:

java

enums

Why does javac add values() and valueOf(String) methods to the enum type being defined? Wouldn't it have been better that they were added to Enum class itself?

What I mean is, if I have some enum such as

enum FooEnum {ONE, TWO}

javac adds values() and valueOf(String) to FooEnum when compiling it. I find it a bit odd. What is the reason behind this?

Is it only to ensure type safety of the returned value/values or is there anything else? And if it's for type safety alone, wouldn't Generics have helped?

like image 417
shrini1000 Avatar asked Oct 03 '12 07:10

shrini1000


People also ask

What is the purpose of values () method in enum?

This method is commonly used in combination with the for-each construct to iterate over the values of an enum type. All the constants of an enum type can be obtained by calling the implicit public static T[] values() method of that type. The values function simply list all values of the enumeration.

What is valueOf method of enum in Java?

valueOf() method returns the enum constant of the specified enumtype with the specified name. The name must match exactly an identifier used to declare an enum constant in this type.

Can enum values be strings?

Given those limitations, the enum value alone is not suitable for human-readable strings or non-string values. In this tutorial, we'll use the enum features as a Java class to attach the values we want.

How do I convert an enum to a string in Java?

There are two ways to convert an Enum to String in Java, first by using the name() method of Enum which is an implicit method and available to all Enum, and second by using toString() method.


1 Answers

They're static methods - how could they have been added to Enum? Static methods aren't polymorphic. Additionally, what would the implementation have looked like in Enum, in your proposed scheme? Enum itself doesn't know the values - only the concrete type does.

like image 65
Jon Skeet Avatar answered Oct 27 '22 04:10

Jon Skeet