枚举以存储RGB字符串

时间:2013-11-08 11:21:10

标签: java enums

我之前从未使用过枚举,所以我发现它们非常令人困惑!我想存储很多RGB值(作为字符串),我认为枚举是最好的选择,而不是列出一堆静态最终字符串的类?我正在试验代码,这是我到目前为止所做的,这是正确的吗? (似乎工作正常)

public enum Colors {
    GREY("142, 142, 147"),
    RED("255, 59, 48"),
    GREEN("76, 217, 100"),
    PURPLE("88, 86, 214"),
    LIGHTBLUE ("52, 170, 220");    //... etc, this is a shorted list

    private Colors(final String string) {
        this.string = string;
    }

    private final String string;

    public String getRGB() {
        return string;
    }
}

public class HelloWorld{
    public static void main(String[] args) {

        String test = Colors.LIGHTBLUE.getRGB();
        System.out.println(test);

    }
}

3 个答案:

答案 0 :(得分:6)

或许将其更改为以下内容:

public enum Colors {
    GREY(142, 142, 147),
    RED(255, 59, 48),
    GREEN(76, 217, 100),
    PURPLE(88, 86, 214),
    LIGHTBLUE (52, 170, 220);    //... etc, this is a shorted list

    private final int r;
    private final int g;
    private final int b;
    private final String rgb;

    private Colors(final int r,final int g,final int b) {
        this.r = r;
        this.g = g;
        this.b = b;
        this.rgb = r + ", " + g + ", " + b;
    }

    public String getRGB() {
        return rgb;
    }

    //You can add methods like this too
    public int getRed(){
        return r;
    }

    public int getGreen(){
        return g;
    }

    public int getBlue(){
        return r;
    }

    //Or even these
    public Color getColor(){
        return new Color(r,g,b);
    }

    public int getARGB(){
        return 0xFF000000 | ((r << 16) & 0x00FF0000) | ((g << 8) & 0x0000FF00) | b;
    }
}

通过分别存储三个组件(以及整数),您可以对它们进行大量有用的操作。

请注意如何轻松地单独提取这三个组件并使用其他方法(例如将它们作为单个ARGB整数检索更容易实现)。

答案 1 :(得分:2)

代码看起来不错,但更好的方法是将RGB值保持为数字(因为它们确实是数字)。您可以重写代码:

public enum Colors {
GREY(142, 142, 147),
RED(255, 59, 48),
GREEN(76, 217, 100),
PURPLE(88, 86, 214),
LIGHTBLUE (52, 170, 220);    //... etc, this is a shorted list

private Colors(final Integer red, final Integer green, final Integer blue) {
    this.red = red;
    this.green = green;
    this.blue = blue;
}

private final Integer red, green, blue;

public String getRGB() {
    return red + "," + green + "," + blue;
}
}

public class HelloWorld{
public static void main(String[] args) {

    String test = Colors.LIGHTBLUE.getRGB();
    System.out.println(test);

}
}

答案 2 :(得分:1)

请改用此枚举:

public enum COLOR {
    GREY(142, 142, 147);

    private int red;
    private int blue;
    private int green;

    private COLOR(int r, int g, int b) {
        this.red = r;
        this.green = g;
        this.blue = b;
    }

    public int getRedValue() {
        return red;
    }

    public int getBlueValue() {
        return blue;
    }

    public int getGreenValue() {
        return green;
    }

    @Override
    public String toString() {
        return red + "," + green + "," + blue;
    }
}