2

I'm trying to create a hierarchy type system using an Enum. I've never used an Enum before.

This method always returns Peasant. I think it's because I am using "this" incorrectly, or maybe I am misunderstanding enums altogether.

public enum Rank {
    PEASANT,
    TRADER,
    SQUIRE,
    MERCHANT,
    KNIGHT,
    NOBLE,
    KING;

    public Rank getNextRank() {
        switch (this) {
        case PEASANT:
            return SQUIRE;
        case SQUIRE:
            return KNIGHT;
        case KNIGHT:
            return NOBLE;
        case NOBLE:
            return KING;
        case KING:
            return PEASANT;
        }
        return PEASANT;
    }
}

(I realize that the KING case isn't necessary, but I like it for readability)

I would like Rank.PEASANT.getNextRank() to return Rank.SQUIRE and Rank.NOBLE.getNextRank() to return Rank.KING, etc.

Jacob Brunson
  • 1,482
  • 4
  • 23
  • 37

2 Answers2

3

Well that code should work, but I'd personally just use ordinal():

public Rank getNextRank() {
    Rank[] allRanks = Rank.values();
    return allRanks[(ordinal() + 1) % allRanks.length];
}

You could avoid calling Rank.values() (which creates a new array on each call) if you use a static final field within the enum, which is set to Rank.values() in a static initializer block.

It would be nice if you could pass the "next rank" to the enum constructor and store it as a field, but that doesn't work in this case as you'd effectively be using a forward reference each time. You could have a non-final field, and set the values in the static initializer, of course:

public enum Rank {
    PEASANT,
    TRADER,
    SQUIRE,
    MERCHANT,
    KNIGHT,
    NOBLE,
    KING,

    private Rank next;

    static {
        PEASANT.next = TRADER;
        TRADER.next = SQUIRE;
        SQUIRE.next = MERCHANT;
        MERCHANT.next = KNIGHT;
        NOBLE.next = KING;
        KING.next = PEASANT;
    }

    public Rank getNextRank() {
        return next;
    }
}

This would be more flexible, for example if you wanted two "equal" ranks which both had the same "next" rank.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
1

I am unable to convey in comments that's its working fine.Please see the pic.

Check the flow again.Problem lies some where else.

System.out.println(Rank.SQUIRE.getNextRank());  //printed KNIGHT

enter image description here

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307