Reputation: 1187
I have this enum
public enum Weekday {
Sunday(0), Monday(1), Tuesday(2), Wednesday(3), Thursday(4), Friday(5), Saturday(6);
private int value;
private Weekday(int value) {
this.value = value;
}
}
And I can get the value from the day if I know what day I want, and I am having a brain freeze right now and am trying to do the oppostie. And cant figure it out
So I know I have number 2 and then want to return a variable of Weekday type Tuesday?
How can I do this?
Thanks for the help :)
Upvotes: 3
Views: 1114
Reputation: 477
Weekday.values()
returns an array with all enum values.
Each enum value has a method ordinal()
, which returns it's index in the enum declaration.
In this case, where the value is equal to the index, you can simplify your code:
public enum Weekday {
Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday;
}
Get the value:
Weekday.Sunday.ordinal()
Get the enum value:
Weekday.values()[value]
Upvotes: 1
Reputation: 15698
You can use Map and then create a method like getByCode
, where you will pass the day number as the argument and it will return you the enum. E.g.
import java.util.HashMap;
import java.util.Map;
enum Weekday {
Sunday(0), Monday(1), Tuesday(2), Wednesday(3), Thursday(4), Friday(5), Saturday(6);
private int value;
Weekday(int c){
this.value =c;
}
static Map<Integer, Weekday> map = new HashMap<>();
static {
for (Weekday catalog : Weekday.values()) {
map.put(catalog.value, catalog);
}
}
public static Weekday getByCode(int code) {
return map.get(code);
}
}
You can call the above method like Weekday.getByCode(2)
and it will return you Tuesday
Upvotes: 3