Java enum序数返回-1?

时间:2014-12-16 05:13:59

标签: java enums ordinal

好吧,我正在为我正在进行的项目编写一些代码,我决定使用Enum进行数据存储将是我最好的选择。但在我生命中的第一次,enum.ordinal()返回-1?

下面是代码:

            DuelRules.Rules rule = DuelRules.Rules.values()[(buttonId - (buttonId < 29 ? 18 : 19))];
            if (buttonId == 29) {
                rule = DuelRules.Rules.POCKET;
            }
            System.out.println(rule + ", " + rule.ordinal());
            rules.swapRule(player, other, rule);
            reset(false);

此声明:

System.out.println(rule + ", " + rule.ordinal());

它打印正确的规则值,但是当它打印rule.ordinal()时,它打印-1?

示例:

HAT, -1

My Enum:

public enum Rules {
    HAT(5000, 1),
    CAPE(5000, 2),
    AMULET(5000, 4),
    WEAPON(5000, 8),
    BODY(5000, 16),
    SHIELD(5000, 32),
    LEG(5000, 128),
    GLOVE(5000, 512),
    BOOT(5000, 1024),
    RING(5000, 4096),
    ARROW(5000, 8192),
    POCKET(17837, 1),

    FORFEIT(4989),
    MOVEMENT(4990),
    RANGE(4991),
    MELEE(4992),
    MAGIC(4993),
    DRINKS(4994),
    FOOD(4995),
    PRAYER(4996),
    OBSTACLES(4997),
    FUN_WEAPONS(4998),
    NO_ABILITIES(4999),
    SUMMONING(5001);

    private final int varbitId;
    private final int value;

    private Rules(int id, int... value) {
        this.varbitId = id;
        this.value = value.length > 0 ? value[0] : 0;
    }

}

注意,枚举是在另一个类中,不确定是否会影响结果。谢谢你的帮助,我完全迷失了这个。

编辑:经过进一步审查,我发现通过将序数作为参数传递来改变序号?

控制台的Screnshot:

代码:

        } else if (buttonId >= 18 && buttonId <= 42) {
           DuelRules.Rules rule = DuelRules.Rules.values()[(buttonId - (buttonId < 29 ? 18 : 19))];
            System.out.println("Point one: "+rule + ", " + rule.ordinal());

            rules.swapRule(player, other, rule);

            getDuel(other).rules.setRules(player, other, rules
                    .rules);
            reset(false);
            sendFlash(interfaceId, buttonId);
        }

在打印第一点的情况下,规则及其.ordinal是正确的,在本例中为OBSTACLES,20

但是它在rules.swapRule中传递了规则参数,它将序数更改为-1?

public boolean swapRule(Player player, Player other, Rules rule) {
    System.out.println("Point 2(swapRule): " + rule + ", " + rule.ordinal());
}

什么导致规则参数在作为参数传递时发生变化?

2 个答案:

答案 0 :(得分:2)

你的认可违背了使用普查员的绝对目的。您可以直接使用Enum,而不是使用索引进行修改

button.setActionCommand (Rules.HAT.toString ());

然后在ActoinListener中,您可以使用此

确定单击了哪个按钮
public void actionPerformed (ActionEvent e) {
    if (Rule.valueOf (e.getActionCommand()) == Rules.HAT) {
        //HAT related button was called, process it
    }
}

答案 1 :(得分:1)

你可以通过反思获得这个结果:

import java.lang.reflect.Field;

public class Main {

    enum Fruit { APPLE }

    public static void main(String[] args) {
        try {
            Field field = Fruit.class.getSuperclass().getDeclaredField("ordinal");
            field.setAccessible(true);
            field.set(Fruit.APPLE, -1);
        } catch (Exception e) {
        }
        System.out.println(Fruit.APPLE + ", " + Fruit.APPLE.ordinal());
    }
}

但我怀疑任何人都可以错误地做到这一点。