简体   繁体   English

Java中具有有限选项的自定义数据类型

[英]Custom data type with limited options, in Java

Trying to create a custom (user-defined) data type, who's value can only possibly be one of a few options, like different states. 尝试创建自定义(用户定义)数据类型时,谁的值只能是少数几个选项之一,例如不同的状态。 Something like: 就像是:
trafficLight = [ "red" | "amber" | "green" ];
or 要么
coin = [0.01 | 0.02 | 0.05 | 0.1 | 0.2 | 0.5 | 1 | 2];

In these examples I guess trafficLight is just a String with limited options, and similarly, coin and int . 在这些示例中,我认为trafficLight只是一个选项有限的String ,类似地, coinint

I think I need to class for these new data types, but how do I restrict the possible values assigned to variables of these custom data types? 我认为我需要对这些新数据类型进行分类,但是如何限制分配给这些自定义数据类型的变量的可能值?

You could use an enum 您可以使用一个枚举

public enum TrafficLight {
    RED, AMBER, GREEN;
}

as per https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html 按照https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html

As enum is neither String or int you will have to map it to your desired type and this can be done in few different ways eg by calling existing String toString() or defining custom int getValue() method. 由于enum既不是String也不是int您必须将其映射到所需的类型,这可以通过几种不同的方式完成,例如,通过调用现有的String toString()或定义自定义int getValue()方法。

How about using enum. 如何使用枚举。 Below is an example of how it could be used. 以下是如何使用它的示例。 By using enum as the parameter to your methods, you restrict the values to only what the enum allows. 通过将枚举用作方法的参数,可以将值限制为仅枚举允许的值。

public class MyNewType {

    public void someMethod(TrafficLight tl, Coin coin) {
        //do something
    }

    public static enum TrafficLight {
        red, amber, green;
    }

    public static enum Coin {
        oneCent(.01f), twoCent(.02f), fiveCent(.05f), tenCent(.1f), fiftyCent(.5f), oneDollar(1f), twoDollar(2f);

        private Coin(float amount) {
            this.amount = amount;
        }
        float amount;

    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM