开发者

enum duration question

开发者 https://www.devze.com 2023-02-15 04:36 出处:网络
So if we have an enum like: public enum light { red, yellow, green } What would be the duration? Isn\'t it the time t开发者_高级运维he light is a certain color?

So if we have an enum like:

  public enum light { red, yellow, green }

What would be the duration? Isn't it the time t开发者_高级运维he light is a certain color?

Like

int duration = ligt.red = 1

or something like that?


Declare your enum like this:

public enum Light { 
    RED(1), 
    YELLOW(2), 
    GREEN(3);

    private final int duration;

    Light(int duration) {
        this.duration = duration;
    } 

    public int getDuration() {
        return this.duration;
    }
}

Then you can use it like this:

public class Test {
    public static void main(String... args) {
        Light light = Light.RED;
        System.out.println("Duration of RED is: " + light.getDuration());
    }
}

EDIT: Based on Steve Kuo's suggestion, the variable duration has been made final.


Adarshr's answer presumes that duration is a property of the color of the light. If it is instead a property of the color at a particular set of signals, you might use an EnumMap<light, Integer>.

class Signal {
    private EnumMap<light, Integer> durations = new EnumMap<light, Integer>(light.class);
    Signal() {
        this.durations.put(light.red, 3);
        ....
    }
}
0

精彩评论

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