Tuple Enum in Java

I am very new to Java and wondered and found nothing about it.

Can you create a root set?

public enum Status {OPEN : "1", CLOSED: "2", DELETED: "3"}

I need to access "OPEN" or "1"

+4
source share
3 answers

You can always create your own constructor for your enum..

public enum Status {


    OPEN("1"),
    CLOSED("2"),
    DELETED("3");

    private String code;

    public Status(String code) {
        this.code = code;
    }

    public String getCode() {
        return code;
    }
}

Then you can access with Status.OPEN.getCode(). It acts as an effective mapping between type enumand value code.

+9
source

@Christopher's solution covers only the first part. Creating ENUM.

You will need another method corresponding to the code with the enum parameter:

public static Status byCode(String code){                            
    for(Status s : Status.values()) {                         
        if (s.code.equals(code)) {                            
            return s;                                         
        }                                                     
    }                                                         

    throw new IllegalArgumentException("Code does not match");
}    

Now you can get the enumeration value by name and code.

+1

- : -

public enum Currency {PENNY(1), NICKLE(5), DIME(10), QUARTER(25)};

But for this you need to define a member variable and constructor, because PENNY (1) actually calls the constructor, which takes an int value, see the example below.

public enum Currency {
        PENNY(1), NICKLE(5), DIME(10), QUARTER(25);
        private int value;

        private Currency(int value) {
                this.value = value;
        }
};  

The enum constructor in java must be private, any other access modifier will lead to a compilation error. Now, to get the value associated with each coin, you can define the public getValue () method inside java enum, like any normal java class. In addition, no more than half of the colon can be used in the first line.

 private int getValue() { return value; }

and get these values: -

PENNY.getValue(); //returns int 1

Renouncement:

0
source

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


All Articles