I'd like to assign a set of variables in java as follows:
int n1,n2,n3;
for(int i=1;i<4;i++)
{
n<i> = 5;
}
How can I achieve this in Java?
This question is related to
java
variables
dynamic-variables
You don't. The closest thing you can do is working with Maps to simulate it, or defining your own Objects to deal with.
Dynamic Variable Names in Java
There is no such thing.
In your case you can use array:
int[] n = new int[3];
for() {
n[i] = 5;
}
For more general (name, value)
pairs, use Map<>
What you need is named array. I wanted to write the following code:
int[] n = new int[4];
for(int i=1;i<4;i++)
{
n[i] = 5;
}
You should use List
or array
instead
List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(2);
list.add(3);
Or
int[] arr = new int[10];
arr[0]=1;
arr[1]=2;
Or even better
Map<String, Integer> map = new HashMap<String, Integer>();
map.put("n1", 1);
map.put("n2", 2);
//conditionally get
map.get("n1");
If you want to access the variables some sort of dynamic you may use reflection. However Reflection works not for local variables. It is only applyable for class attributes.
A rough quick and dirty example is this:
public class T {
public Integer n1;
public Integer n2;
public Integer n3;
public void accessAttributes() throws IllegalArgumentException, SecurityException, IllegalAccessException,
NoSuchFieldException {
for (int i = 1; i < 4; i++) {
T.class.getField("n" + i).set(this, 5);
}
}
}
You need to improve this code in various ways it is only an example. This is also not considered to be good code.
Try this way:
HashMap<String, Integer> hashMap = new HashMap();
for (int i=1; i<=3; i++) {
hashMap.put("n" + i, 5);
}
Source: Stackoverflow.com