How do I create new variables based on the size of the list?

I have one List

with specified size n and I have to create variables dynamically n

, i.e. I want to dynamically create variables based on the size of the list. How can I achieve this?

Let's say I have List

both List<Integer> year

n elements in it;

then I have to create n variables Integer

from the above list.

EDIT: If I have a list of 3 items in it, I want to create 3 variables, like

a = list(0);
b = list(1);
c = list(2);

      

as this list can have any number of elements, then I have to create these many variables. I hope I get it now.

thanks.

+2


a source to share


2 answers


You cannot create local variables n

as you seem to be suggesting. (What would their names be?)

You need to store variables (or rather integer values) in List

or some other Collection

, and fill them in a loop:

int n = year.size();
List<Integer> theIntegers = new ArrayList<Integer>(n);
for (int i = 0; i < n; i++)
    theIntegers.add(i);

      

gives you the year.size()

number of integers (0, 1, 2, ...).

Then you can access the integers via

theIntegers.get(4);

      



if you want to read the integer at index 4. and

theIntegers.set(4, 10);

      

if you want to update the integer at index 4 to value 10.


In this case, you can also create an array:

int[] ints = new int[year.size()];
for (int i = 0; i < ints.length; i++)
    ints[i] = i;

      

+7


a source


There is no way in Java so that I can add variables to scope dynamically. You can use a map as the type of a variable ... well, a mapping instead:



final List<Integer> years = getYearList();
final Map<String, Integer> yearMapping = new HashMap<String, Integer>();
for(int year : years)
{
    final String name = generateNameForYear(year);
    yearMapping.add(name, new Integer(year));
}

// Later... Get "variables" out of the map:
final String variableName = "fooYear";
if (yearMapping.containsKey(variableName))
{
    final Integer variableValue = yearMapping.get(variableName);
}
else
{
    // "variable" does not exist.
}

      

0


a source







All Articles