3

我以前从未使用过枚举,所以我发现它们非常混乱!我想存储很多 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);

    }
}
4

3 回答 3

7

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

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 整数检索更容易实现)。

于 2013-11-08T11:30:25.580 回答
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);

}
}
于 2013-11-08T11:28:37.213 回答
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;
    }
}
于 2013-11-08T11:29:18.513 回答