Get weekday from int

I have this listing

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 value from the day if I know what day I want and now my brain is frozen and I am trying to make an oppostie. And I can't figure it out

So I know I have number 2 and then want to return a variable of type Weekday type Tuesday?

How can i do this?

Thanks for the help:)

+3


source to share


2 answers


You can use a map and then create a type method getByCode

where you pass the day number as an argument and it will return you an enum. For example.

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 for example Weekday.getByCode(2)

and it will return youTuesday

+3


source


Weekday.values()

returns an array with all the enumeration values. Each enumeration value has a method ordinal()

that returns it in the enumeration declaration.

In this case, when the value is equal to the index , you can simplify your code:

public enum Weekday {
    Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday;
}

      

Get value:



Weekday.Sunday.ordinal()

      

Get enum value:

Weekday.values()[value]

      

+1


source







All Articles