Looking to associate strings to ints in a cleaner/more efficient way

前端 未结 8 967
孤街浪徒
孤街浪徒 2021-01-07 07:06

How can I improve this?

The relationship is one to one and continuous on [-1,5] so i was thinking of using enum, but I\'m not sure how to compare a string value to

相关标签:
8条回答
  • 2021-01-07 07:55

    Why do you need a (very subjective) "cleaner" way?

    You could get more efficiency from using a hash lookup but you'd want to be certain it's called quite a bit to make the extra coding effort worthwhile. If it's something that happens infrequently (and, by that, I mean something like less than once a second), it's not worth doing (YAGNI).

    One thing you might want to do for better looking code (if that's important) is to ditch the else bits, they're totally unnecessary:

    private int evaluateWord(String sval) {
        if (sval.equals("program")) return 1;
        if (sval.equals("begin"))   return 2;
        if (sval.equals("end"))     return 3;
        if (sval.equals("int"))     return 4;
        if (sval.equals("if"))      return 5;
        System.exit(0);
    }
    
    0 讨论(0)
  • 2021-01-07 07:57

    Have you considered stuffing the mapping into a HashMap once, and then just querying the map?

    For example, something like this:

     private static final Map<String,Integer> m_map = new HashMap<String,Integer>();
     static {
         m_map.put( "program", 1 );
         m_map.put( "begin", 2 );
         m_map.put( "end", 3 );
         m_map.put( "int", 4 );
         m_map.put( "if", 5 );
     }
    
     private int evaluateWord(String sval) {
         Integer value = m_map.get( sval );
         if ( null != value ) {
            return value;
         }
         else {
            System.exit(0);
         }
     }
    

    By the way, it looks as if you're writing a parser. It can be reasonable to write a parser by hand. Another option to consider, unless you have a good reason to write it by hand, is a parser generator like ANTLR.

    0 讨论(0)
提交回复
热议问题