kcarew98
kcarew98

Reputation: 17

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.

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?

Upvotes: 1

Views: 1248

Answers (2)

Karol Dowbecki
Karol Dowbecki

Reputation: 44952

You could use an enum

public enum TrafficLight {
    RED, AMBER, GREEN;
}

as per 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 e.g. by calling existing String toString() or defining custom int getValue() method.

Upvotes: 2

Jose Martinez
Jose Martinez

Reputation: 11992

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;

    }

}

Upvotes: 2

Related Questions