【问题标题】:How to map String variable to name of an integer? [duplicate]如何将字符串变量映射到整数名称? [复制]
【发布时间】:2022-01-03 21:19:13
【问题描述】:

假设我在 Java 中有一个这样的字符串变量:

字符串 cat = "felix";

int felix = 6;

在 Java 中有什么方法可以比较 cat - "felix" 的内容和 int 变量 felix 的名称吗?

【问题讨论】:

  • 不,没有。至少没有变量名。但是,我们可以使用Map<String, Integer>

标签: java string integer mapping


【解决方案1】:

用你做的方法没办法,但是可以用hashmap:

Map<String,Integer> myMap = new HashMap<>();
myMap.put("felix", 6);
myMap.put("another key", -4);
int value = myMap.get("felix");
System.out.println(value);//prints 6
value = myMap.get("abc");//throws null pointer exception

【讨论】:

  • 这种方法不是null-safe。如果给定String 的映射不存在,它将抛出NullPointerException (Ideone demo)。这也不是OP所要求的。我们宁愿在 cmets 中要求澄清,而不是张贴推测性的答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-02-21
  • 2022-08-16
  • 1970-01-01
  • 2014-05-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-09
相关资源
最近更新 更多