帮助Java中的枚举

前端之家收集整理的这篇文章主要介绍了帮助Java中的枚举前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
是否有可能让枚举更改其值(从内部)?也许更容易理解代码的含义:
enum Rate {
    VeryBad(1),Bad(2),Average(3),Good(4),Excellent(5);

    private int rate;

    private Rate(int rate) {
        this.rate = rate;
    }

        public void increateRating() {
            //is it possible to make the enum variable increase?
            //this is,if right now this enum has as value Average,after calling this
            //method to have it change to Good?
       }
}

这是我想要实现的目标:

Rate rate = Rate.Average;
System.out.println(rate); //prints Average;
rate.increaseRating();
System.out.println(rate); //prints Good

谢谢

解决方法

是.你可以简单地打电话
rate = Rate.Good;

对于这个特定的情况.但我认为你真正想要的是继任功能.

Here你是:

public class EnumTest extends TestCase {
    private enum X {
        A,B,C;
        public X successor() {
                return values()[(ordinal() + 1) % values().length];
        }
    };

    public void testSuccessor() throws Exception {
        assertEquals(X.B,X.A.successor());
        assertEquals(X.C,X.B.successor());
        assertEquals(X.A,X.C.successor());
    }
}

猜你在找的Java相关文章