ZigZagZebra
ZigZagZebra

Reputation: 1459

Represent a list of constants in java

I hope to manage static final String from "0" to "1" so that when I encounter a String counterpart, I can easily replace it with the constant. Right now the best I can do is to declare all the constants at the beginning of the class:

private static final String ZERO = "0";
private static final String ONE = "1";
private static final String TWO = "2";
...

But then for a String, I have to check the value of it (e.g. if it is one of "0" to "1") and then replace it with corresponding constant. I'm wondering if there is a better way to handle this?

This is used as an input of an API. The API requires String that is a compile time constant. For example if the string I obtained is "1" then I will input ONE (which is a constant string "1" ) to the API.

Upvotes: 0

Views: 11205

Answers (2)

Remario
Remario

Reputation: 3863

Yes there is, use enums.

public enum NumberValues { ONE, TWO, THREE, FOUR }  

for (Numbervalues num : NumberValues.values())  
    System.out.println(num);

Output:

ONE
TWO
THREE
FOUR

to get the value of the Enum use

System.out.println(num.ordinal());

for more detailed introspection please visit.https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html

Upvotes: 4

Darshan Mehta
Darshan Mehta

Reputation: 30819

You can write an enum like this:

enum Constants{

    ONE("1"),
    TWO("2");

    private final String value;

    private Constants(String value){
        this.value = value;
    }

    public static Constants findByValue(String value){
        for(Constants constants : values()){
            if(constants.value.equals(value)){
                return constants;
            }
        }
        return null;
    }

    public String getValue() {
        return value;
    }
}

Once you encounter a string (let's say "1"), you can check whether any enum is defined for it (with findByValue method) and if the result is not null, you can replace the value, e.g.:

public static void main(String[] args) throws Exception{
    String s = "1";
    Constants constant = Constants.findByValue(s);
    if(null != constant){
        s = s.replaceAll(constant.getValue(), constant.name());
    }
    System.out.println(s);
}

Upvotes: 2

Related Questions