public enum Role{
ADMIN("SMITH","KEVIN"),
STUDENT("JACK", "JILL", "MARRY", "MALA"),
GURDIAN("BOB");
}
How can I define constructor for this enum in JAVA?
Can I initiate as follows?
Role(List<String> userlist){}
The most suitable constructor I can think of is with a String
varargs, as follows:
Role(String... names) {
// TODO
}
A constructor taking List<String>
will not match the signature and will not compile on its own.
You can always overload the constructors though.
You definitely go with the varargs style constructor
private final List<String> values;
Role(String... values) {
this.values = Arrays.asList(values);
}
public List<String> getValues() {
return values;
}
And then when you need the particular role based on the provided names go for the find as
public static Role find(String name) {
for (Role role: Role.values()) {
if (rol.getValues().contains(name)) {
return rol;
}
}
return null;
}
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