Question

My professor wants us to make an enum called MedicalSpecialty, with GENERAL_MEDICINE, PEDIATRICS, and ONCOLOGY as members of the enumeration (so far so good).

Then he wants us to define a method called getFromString inside the MedicalSpecialty enum "that takes a String parameter and returns a MedicalSpecialty with the same name as the String parameter"

I'm not sure what he means, but then he says:

"Hint: use the toString() method from the MedicalSpecialty enum to perform your checks"

I'm not looking for a solution, but rather an explanation of what he is asking, if anyone understands. Is the getFromString method meant to take in a String like "general_medicine" and then output "GENERAL_MEDICINE" as type MedicalSpecialty? That seems useless and probably wrong...

Any help would be appreciated!

Was it helpful?

Solution

You have the right idea. Think of it this way:

Suppose you are designing a system that works with components that function across the globe and you use the internet to communicate between them. A component in Europe, wants to request a new doctor of Oncology to be transferred from the US component. It can't send a MedicalSpeciality enum over the wire, so instead it sends a String, e.g. "Oncology". Now, in the code of your US component, you want to translate that piece of text to something that your US component system understand: the enum.

You need to write a method that takes the input String sent over the wire and returns the corresponding Enum value.

OTHER TIPS

He means that valid input for your function will be the following:

"GENERAL_MEDICINE", "PEDIATRICS", "ONCOLOGY"

Your task is to convert the type String to the type Enum.

He probably wants you to show that you know how to loop through all the elements of an enum and compare each toString result to the passed in string.

You're right, that's not the best way to do it.

public enum Medicine {

    GENERAL_MEDICINE("general_medicine"), 
    PEDIATRICS("pediatrics");

    private final String value;

    Medicine(String v) {

        value = v;
    }

    public String value() {
        return value;
    }

    public static Medicine fromString(String v) {
        for (Medicine c : Medicine.values()) {
            if (c.value.equals(v)) {
                return c;
            }
        }
        throw new IllegalArgumentException(v);
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top