首页 > 解决方案 > 将字符串分配给 int

问题描述

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

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

我可以做类似的事情

intToStr(1) = "苹果"

或者

StrToInt("香蕉") = 2

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

标签: java

解决方案


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

  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

资源:


推荐阅读