Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default Enumeration Methods

Tags:

java

enums

An enum contains the name and valueOf methods.

Agian we know that the Java Compiler automatically generates a static method for each enum, called values.

This method returns an array of all constants defined inside the enum.

As there is an static method values, then why should we use name() method? Then what are the difference between the static method values() and the valueof() method?

like image 626
Light Avatar asked Dec 10 '25 09:12

Light


1 Answers

Read their javadoc (Thread.State, for example, inheriting Enum, like all the enums), and you'll see what they're for.

name() is an instance method which returns the name of the instance.

valueOf() is a static method taking a String and returning the enum instance with that name.

values() is a static method returning all the enum instances.

like image 71
JB Nizet Avatar answered Dec 11 '25 22:12

JB Nizet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!