Best way to list Java

I'm interested in learning about a good enumeration method in Java.

I have been asking this for a long time, and usually I come up with something that includes several independent enumerations and functions, and some define, etc.

But basically, I want to define unique numeric keys for various types of enumerations, with sub enumerations.

For example, I am trying to implement a language with various keywords and characters with a number corresponding to this element in brackets. As an element (id).

Keywords: program (1), call (2), if (3), else (4), elsif (5), ... Symbols ';' (6), ',' (7), '=' (8), '+' (9), ... Operations: and (10), or (11), ...

What would be the best way to achieve this?

I hope my messages were clear. But basically, I'm trying to create categories of element types, and then define elements inside them that have a related numeric value.

The purpose of this would be so that I could check the input string to return an integer value if it identified the substrings in the input as elements in the "dictionary" above.

Thanks in advance!

+5
source share
4 answers

, . , - , , . , , .

"" ( ), - . , , :

public interface Operators {
}

public enum BooleanOperators implements Operators {    
   AND, OR, NOT, XOR
}

public enum ArithmeticOperators implements Operators {
   ADD, SUBTRACT, MULTIPLY, DIVIDE
}

, BooleanOperators , ArithmeticOperators, , Operators:

public void doSomethingWithOperators(Operators operators) {
    ....
}

, :

public interface Operators {
    int getCode();
}

public enum BooleanOperators implements Operators {

   private int code;

   AND(1), OR(2), NOT(3), XOR(4)

   private BooleanOperators(int code) {
       this.code = code;
   }

   public int getCode() {
       return this.code;
   }
}

ArithmeticOperators.ADD.getCode(), , . , , , . , - , (, ) .

. ; , , , getCode(). :

public enum BooleanOperators {

   private int code;

   AND(1), OR(2), NOT(3), XOR(4)

   private BooleanOperators(int code) {
       this.code = code;
   }

   public int getCode() {
       return this.code;
   }
}

, , . , !

, ( Token), , Map<String, Token>. . , .

+3

EnumSet enum; .

+1

A good solution, but when you implement operators, take care of their priority, which can also be an enum parameter. My approach was to use a separate group for each priority level, and when I add them to the parser, I add them in order of priority.

0
source

All Articles