[Q#19336202][A#19336268] How to create variables dynamically in Java?
https://stackoverflow.com/q/19336202
I need to create new variables Strings such that This is what I tried Can anybody help me correct this code?
Answer
https://stackoverflow.com/a/19336268
A Map allows you to relate any key with any value. In this case, the key is the name of the variable, and the value is the value
APIzation
Map<String, String> details = new HashMap<>();
for (int i = 1; i <101; i++) {
if (i<60) {
details.put("person" + i, "female");
}
else {
details.put("person" + i, "male");
}
}
package com.stackoverflow.api;
import java.util.HashMap;
import java.util.Map;
public class Human19336268 {
public static void createMap() {
Map<String, String> details = new HashMap<>();
for (int i = 1; i < 101; i++) {
if (i < 60) {
details.put("person" + i, "female");
} else {
details.put("person" + i, "male");
}
}
}
}
package com.stackoverflow.api;
import java.util.HashMap;
import java.util.Map;
/**
* How to create variables dynamically in Java?
*
* @author APIzator
* @see <a href="https://stackoverflow.com/a/19336268">https://stackoverflow.com/a/19336268</a>
*/
public class APIzator19336268 {
public static void createVariable() throws Exception {
Map<String, String> details = new HashMap<>();
for (int i = 1; i < 101; i++) {
if (i < 60) {
details.put("person" + i, "female");
} else {
details.put("person" + i, "male");
}
}
}
}