2

I coded to populate my enum with Friendly String names, e.g. Swimming Time, Hiking Time...

public enum SeasonTypeEnum {
    summer("Swimming Time"),
    auturm("Hiking Time"),
    winter("Skiing Time"),
    spring("Planting Time");

    private String friendlyName;

    private SeasonTypeEnum(String friendlyName){
        this.friendlyName = friendlyName;
    }

    @Override
    public String toString(){
        return friendlyName;
    }
}

However, I'm thinking of storing these stings in an array and extracting from there. How could I do that?

3 Answers 3

3

Most likely an enum is the best solution however,

The way I would write an array like this

static final String[] seasons = 
              "Swimming Time,Hiking Time,Skiing Time,Planting Time".split(",");

if you want to extract from the enums you can do this

static final SeasonTypeEnum[] VALUES = values();

public static String friendlyNameFor(int id) {
    return VALUES[id].friendlyName;
}
Sign up to request clarification or add additional context in comments.

2 Comments

Or just call values(); unless the code makes millions of calls per second, the performance gain by creating the constant array will be negligible.
@AaronDigulla Since your IDE can do this refactor for you, I would write it as value()[id] but use the Introduce a Constant refactor.
2

You can use Enum.values() for this.

Example:

SeasonTypeEnum[] vals = SeasonTypeEnum.values();
String[] strs = new String[vals.length];
for (int i = 0; i < vals.length; i++) {
   strs[i] = vals[i].toString();
}

Or the other way around:

   public static SeasonTypeEnum getByStr(String val) {
      for (SeasonTypeEnum e : values()) {
         if (e.friendlyName.equals(val)) return e;
      }

      return null;
   }

Comments

1

You can store friendly strings in private static array and correlate with enum entries by adding index as entry field:

public enum SeasonTypeEnum {

    private static String seasons = new String[] {"Swimming Time", "Hiking Time", "Skiing Time", "Planting Time"};

    summer(0),
    auturm(1),
    winter(2),
    spring(3);

    private int index;

    private SeasonTypeEnum(int index) {
        this.index = index;
    }

    @Override
    public String toString() {
        return seasons[index];
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.