【问题标题】:Assigning string to int [duplicate]将字符串分配给 int [重复]
【发布时间】:2019-04-25 02:17:17
【问题描述】:

我想为字符串分配一个 int 值,这样 如果

“苹果”=1,“香蕉”=2

我可以做类似的事情

intToStr(1) = "苹果"

StrToInt("香蕉") = 2

我知道我可以通过使用 switch 语句来做到这一点,但我听说使用太多 switch 语句并不理想。使用一堆 switch 语句可以吗?如果不是,那么进行这种映射的最佳方法是什么?

【问题讨论】:

  • 你要找的是Map<String, Integer>:Map.of("apple", 1, "banana", 2);

标签: java


【解决方案1】:

如果数据是一个常数,也许你可以使用枚举,

  enum Fruit {
    APPLE, BANANA, STRAWBERRY,
  }

Arrays.stream(Fruit.values()).forEach( fruit -> System.out.println(fruit.name() + " - " + fruit.ordinal()));

输出:

APPLE - 0
BANANA - 1
STRAWBERRY - 2

如果没有,地图将解决您的要求:

Map<String, Integer> fruits = new HashMap<>();

    fruits.put("APPLE", 1);

    fruits.put("BANANA", 2);

    fruits.put("STRAWBERRY", 3);

    fruits.forEach((x,y)->System.out.println(x + " - " + y));

输出:

APPLE - 1
BANANA - 2
STRAWBERRY - 3

来源:

【讨论】:

    【解决方案2】:

    根据具体情况,有多种工具可用于解决此问题:

    1. 您已经建议的switch 声明。

    2. 一个enum

    3. Map&lt;String, Integer&gt;

    【讨论】:

      【解决方案3】:

      这里有一些选项。

      enum MyEnum {
         Apple(1), Banana(2), Orange(3);
         private int v;
      
         private MyEnum(int v) {
            this.v = v;
         }
      
         public int getValue() {
            return v;
         }
      }
      
      public class SimpleExample {
      
         public static void main(String[] args) {
            // You could do it with a Map. Map.of makes an immutable map so if you
            // want to change those values, pass it to a HashMap Constructor
      
            Map<String, Integer> map = new HashMap<>(Map.of("Apple", 1, "Banana", 2));
            map.entrySet().forEach(System.out::println);
      
            for (MyEnum e : MyEnum.values()) {
               System.out.println(e + " = " + e.getValue());
            }
      
         }
      }
      

      【讨论】:

        猜你喜欢
        • 2014-10-10
        • 1970-01-01
        • 2012-01-11
        • 1970-01-01
        • 1970-01-01
        • 2020-07-23
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多