Setting enumeration and parsing values ​​to get an enumeration

My listing is as follows:

public enum Manufacturers {
  Honda,
  GM,
  Toyota,
  Ferrari
}

I need to create a Hashmap, so I plan to do this, is this correct?

Manufacturers mfg = Manufacturers.Honda;

mfg.ordinal()  // save as key

i.e. I will save the key usingenumInstance.ordinal()

In addition, I need to be able to parse the string, which will be the ordinal value of the enumeration, and get the enumeration back:

Manufacturers mfg = Manufacturers.valueOf(mfgOrdinalValueAsString);

The above gave me an error (line was "1"). Is it correct? Think I should try / catch there?

+5
source share
2 answers

.valueOf would really expect the string "GM" (for 1).

, EnumMap, , .

, - Manufacturers.values()[1].

+2

: name(), String, , Enum , valueOf() - valueOf() , , . :

enum Example {ONE, TWO};

String name = Example.ONE.name();
Example e = Example.valueOf(Example.class, name);  // e has value ONE

, ordinal() , Enum , values(). :

int ordinal = Example.ONE.ordinal();
Example e = Example.values()[ordinal];  // e has value ONE

, EnumMap, ,

enum. , , , . Enum . .

( ), , :

public enum Manufacturers {

    Honda(10),
    GM(20),
    Toyota(30),
    Ferrari(40);

    private int code;

    Manufacturers(int code) {
        this.code = code;
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

}

:

Manufacturers m = Manufacturers.Honda;
System.out.println(m.getCode()); // prints 10
m.setCode(100);
System.out.println(m.getCode()); // prints 100

, Enum code, .

+2

All Articles