How to create variables dynamically in Java? [closed]

Solution 1:

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

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");
    }
}

Solution 2:

You are close. If you store the the gender of each person in an array, you can do it like this:

String[] persons = new String[100]
for (int i = 0; i < persons.length; i++) {
  if (i<60) {
    persons[i] = "female";
  }
  else {
    persons[i] = "male";   
  }
}

Alternately, if a person is more than a gender, consider making a class Person that holds a gender field, and then have an array of Persons. You would set the gender in a similar way.

Solution 3:

You might use a Map<String,String> where the key is your "variable name" and the value is the value of that variable.

Solution 4:

You will need a String[] of some size that you can determine dynamically.
Then, assign values to the array elements.

String[] anArray;

// some magic logic

anArray = new String[100];
for(int i = 0; i < anArray.length; i++){
 // more magic logic to initialize the elements
}  

Another option is a Vector<> or ArrayList<> like so:

List<String> anExpandableArray = new ArrayList<String>();
// add String data
anExpandaleArray.add("Foo");
anExpandaleArray.add("Bar");

Solution 5:

When you find yourself wanting to create "more variables" of the same type, you usually want a list of some kind. There are two fundamental kinds of "lists" in Java: Arrays, and Lists.

An array:

String[] people = new String[10];               // That gives you room for 10

people[0] = "female";
people[1] = "male";
// ...
int n = 1;
System.out.println("Person " + n + " is " + people[n]);

A List:

List<String> people = new LinkedList<String>(); // Expandable
people.add("female");
people.add("male");
// ...
int n = 1;
System.out.println("Person " + n + " is " + people.get(n));
// Note difference -------------------------------^^^^^^^

Using an array is great when you know in advance how many there will be. Using a list is great when you don't know how many there will be.

Note on lists: There's an interface, List, and then there are multiple different concrete implementations of it with different runtime performance characteristics (LinkedList, ArrayList, and so on). These are in java.util.