Why does valueOf
have two parameters?
in Java documentation for valueOf
public static <T extends Enum<T>> T valueOf(Class<T> enumType, String name)
Parameters:
enumType - the Class object of the enum type from which to return a constant
name - the name of the constant to return
But most examples I read online says:
enum WorkDays {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY;
}
Test:
WorkDays day1 = WorkDays.valueOf("MONDAY");
System.out.println(day1); // >>> MONDAY
It seems that the method used only one parameter?
The Enum constructor can accept multiple values.
Learn to create Java enum where each enum constant may contain multiple values. We may use any of the values of the enum constant in our application code, and we should be able to get the enum constant from any of the values assigned to it.
valueOf. Returns the enum constant of the specified enum type with the specified name. The name must match exactly an identifier used to declare an enum constant in this type. (Extraneous whitespace characters are not permitted.)
Since you cannot override valueOf method you have to define a custom method ( getEnum in the sample code below) which returns the value that you need and change your client to use this method instead. getEnum could be shortened if you do the following: v. getValue().
As you indicated in previous comments that you find the text in the documentation confusing, and since your profile indicates you are a novice programmer:
Enum is the superclass of all enums you will declare.
In your example, WorkDays can be seen as a specific case of the Enum class.
The valueOf() static method documentation is writen for this parent Enum class.
Meaning that in your case, it would be called as:
Enum.valueOf(WorkDays.class, "MONDAY")
.
Now, since you made your own Enum (i.e. WorkDays), you don't need to use this static parent method. You can just use the method that is exposed by your self-created enum.
WorkDays.valueOf("Monday")
This is "implicitly declared" meaning that there it will be there for every one of your self-created enums.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With