简体   繁体   中英

Define constructor for this enum for the list in JAVA?

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;

}

public enum Role{ 
    ADMIN("SMITH","KEVIN"),
    STUDENT("JACK", "JILL", "MARRY", "MALA"),
    GURDIAN("BOB");

    private String[] values;

    Role(String ... values) {
         this.values = values;
    }
}

You can use use variable arguments varargs in constructor like:

public enum Role {

    ADMIN("SMITH","KEVIN"),
    STUDENT("JACK", "JILL", "MARRY", "MALA"),
    GURDIAN("BOB");

    private Role(String...name) {
        this.values = name;
    }
}

There is declaration (in enum), storage in field, and usage.

As these are singletons, defined in the enum class, the form of the declaration is only important with respect to elegance.

public enum Role{ 
    ADMIN(user("SMITH", "KEVIN")),
    STUDENT(user("JACK", "JILL"), user("MARRY", "MALA")),
    GURDIAN(user("BOB"));

    // Local factory methods
    // User or Principal
    private User user(String firstname, String surname) { ... }
    private User user(String firstname) { ---}

    private final Set<User> users;

    Role(User... users) {
        if (users.length == 1) { ...
        }
        this.users = new HashSet<>();
        Collections.addAll(users);
    }

    public boolean ...(...) {
        ...
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM