Java Enums provide uniqueness for the field

I have an enumeration that in a simplified form looks like this.

public enum Codes{
    Code1("someCode1", "someState"),
    Code2("someCode2", "someState"),
    ...
    ...
    private final String m_code;
    private final String m_state;       
}

My goal - to ensure that when someone else is editing this listing to add a new value, for example Code100, m_codefor Code100should not be the same as m_codefor any of the previous Code1- Code99. The only way I could think of is to write a unit test for this listing, which will do this check. Is there a better solution to this problem?

Ideally, I would like a compile-time error for this situation, but I'm not sure if this can be done in Java?

+4
source share
3

m_code ?

Try

public enum Codes{
  someCode1("someState"),
  someCode2("someState"),
  ...
  ...
  private final String m_state;       
}

enum . , , , , , , .

+4

, . Code1 Code99, :

public enum Codes {
    CODE1("someCode1", "someState"),
    CODE2("someCode2", "someState"),
    //...
    //...
    CODE99("someCode99", "someState");

    static {
        Set<String> codes = new HashSet<>();
        for (Codes value : values()) {
            if (!codes.add(value.code)) {
                throw new RuntimeException(
                    "Duplicate code string value: \"" + value.code + "\"");
            }
        }
    }

    private final String code;
    private final String state;
}
+1

stick to what should be unique in the static set, and make sure you add this to the constructors so that all this is done at boot time.

0
source

Source: https://habr.com/ru/post/1667582/


All Articles