0

I have an enumerator that takes an int and a string as fields. These are accessible via static methods or directly from the enumerator "instance" (not familiar with the proper wording for this). Here is what I mean by that:

public enum CreatureType {

    POKE_PIG(1, "Piggley"), POKE_COW(2, "Cowbert");

    private int number;
    private String name;

    CreatureType(int number, String name) {
        this.number = number;
        this.name = name;
    }

    public int getNumber() {
        return number;
    }

    public String getName() {
        return name;
    }

    public static String getName(CreatureType type) {
        return type.getName();

    }

    public static int getNumber(CreatureType type) {
        return type.getNumber();
    }

But now I need to get a CreatureType FROM it's int. So here's my pseudocode I've written that is my best guess at how to do this:

public static CreatureType getCreatureType(int number) {
    switch (number) {
    case 1:
        return CreatureType.POKE_PIG;
    case 2:
        return CreatureType.POKE_COW;
    default:
        break;
    }
    return null;

}

This feels weird though. I don't love this technique, and even though in theory it should work, I feel like there HAS to be a better way of doing this. I don't have these enums stored in a list or set or anything so I can't iterate through them, and I'm just blanking on the proper way to grab this.

khelwood
  • 55,782
  • 14
  • 81
  • 108
  • https://stackoverflow.com/q/11047756/438992 – Dave Newton Sep 07 '21 at 20:18
  • Each `Enum`-value has an implicit `int`-value, although I can understand one would not want to use it in this case. --- We can use `Stream`-operations to get a `CreatureType` with a given `number`: `Arrays.stream(CreatureType.values()).filter(creature -> creature.getNumber() == number).findAny();`. This will return an `Optional` that is empty if no creature with the given number is found and an non-empty `Optional` otherwise. – Turing85 Sep 07 '21 at 20:21
  • [Ideone demo](https://ideone.com/8XRwVu) – Turing85 Sep 07 '21 at 20:28

1 Answers1

0

Your switch-case solution is more efficient, but the following code is easier to maintain as it does not need adjustment when adding a new enum value:

public static CreatureType getCreatureType(int number) {
    for(CreatureType creatureType : CreatureType.values()) {
        if(creatureType.number == number) {
            return creatureType;
        }
    }
    return null; // No match.
}
Pieter12345
  • 1,713
  • 1
  • 11
  • 18