枚举以存储RGB字符串

Mat*_*eus 2 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);

    }
}
Run Code Online (Sandbox Code Playgroud)

ini*_*mfs 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;
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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