Is it possible to have an enum change its value (from inside itself)? Maybe 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
In Java (from 1.5), enums are represented using enum data type. Java enums are more powerful than C/C++ enums. In Java, we can also add variables, methods, and constructors to it. The main objective of enum is to define our own data types(Enumerated Data Types).
How to Create an Enum in Java. To create an enum , we use the enum keyword, similar to how you'd create a class using the class keyword. In the code above, we created an enum called Colors . You may notice that the values of this enum are all written in uppercase – this is just a general convention.
You should always use enums when a variable (especially a method parameter) can only take one out of a small set of possible values. Examples would be things like type constants (contract status: "permanent", "temp", "apprentice"), or flags ("execute now", "defer execution").
Because there is only one instance of each enum constant, it is permissible to use the == operator in place of the equals method when comparing two object references if it is known that at least one of them refers to an enum constant.
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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With