java - 将字符串分配给 int
问题描述
我想为字符串分配一个 int 值,这样如果
“苹果” = 1,“香蕉” = 2
我可以做类似的事情
intToStr(1) = "苹果"
或者
StrToInt("香蕉") = 2
我知道我可以通过使用 switch 语句来做到这一点,但我听说使用太多 switch 语句并不理想。使用一堆 switch 语句可以吗?如果不是,那么进行这种映射的最佳方法是什么?
解决方案
如果数据是一个常数,也许你可以使用枚举,
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
资源:
推荐阅读
- c# - ICollection 属性和封装
- java - 使用 Spring 获取客户端的浏览器名称和 IP 地址
- asp.net-mvc - 从控制台访问 API 是有效的,但同样不适用于 MVC Web
- ios - 在 iPhone 4s 中播放时,视频最后会冻结
- maven - maven:禁用surefire控制台错误(或修复控制台错误编码)
- angular - 如何使用 Angular 6 拦截器更改 http req url
- angular-material - 如何导入 Angular 材质 Css
- git - 如何硬恢复并再次提交到服务器
- java - JAVA CSV 写空格不带引号
- unit-testing - 测试使用全局事件总线的 Vue 单文件组件