How to map String variable to name of an integer?

456 views Asked by At

Suppose I have a String Variable like this in Java:

String cat = "felix";

int felix = 6;

Is there some way in Java that I could compare the contents of cat - "felix" to the name of the int variable felix?

1

There are 1 answers

1
Ofek On

There is no way to do it with the method you are doing, but you can use 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