开发者

Help with enums in Java

开发者 https://www.devze.com 2022-12-27 14:26 出处:网络
Is it possible to have an enum change its value (from inside itself)? Maybe开发者_C百科 it\'s easier to understand what I mean with code:

Is it possible to have an enum change its value (from inside itself)? Maybe开发者_C百科 it's easier to understand what I mean with code:

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?
       }
}

This is want I wanna achieve:

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

Thanks


Yes. You could simply call

rate = Rate.Good;

for this specific case. But what I think you are really looking for is a successor function.

Here you are:

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());
    }
}


Do you want something like this?

class Rate {
    private static enum RateValue {
        VeryBad(1),
        Bad(2),
        Average(3),
        Good(4),
        Excellent(5);

        private int rate;

        public RateValue(int rate) {
            this.rate = rate;
        }

        public RateValue nextRating() {
            switch (this) { /* ... */ }
        }
    }

    private RateValue value;

    public void increaseRating() {
        value = value.nextRating();
    }
}


The example in the question tries to change the value of "rate" by calling a method on it. This is impossible, enum values are objects, so you cannot change them for the same reasons you cannot assign a new value to "this". The closest thing you can do is add a method that returns another enum value, as proposed by Carl Manaster.


It should be possible but I have to admit that I've never tried it. In the end enums are just objects with a little twist so you should be able to do that unless you define the rate field as final.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号