Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define constructor for this enum for the list in JAVA?

Tags:

java

list

enums

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){}
like image 455
Ted87 Avatar asked Jan 04 '23 09:01

Ted87


2 Answers

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.

like image 156
Mena Avatar answered Jan 06 '23 01:01

Mena


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;

}

like image 26
Rizwan Avatar answered Jan 06 '23 02:01

Rizwan