Assigning variables with dynamic names in Java

2018-12-31 00:01发布

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?

7条回答
大哥的爱人
2楼-- · 2018-12-31 00:10

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");
查看更多
余生无你
3楼-- · 2018-12-31 00:16

Try this way:

    HashMap<String, Integer> hashMap = new HashMap();

    for (int i=1; i<=3; i++) {
        hashMap.put("n" + i, 5);
    }
查看更多
美炸的是我
4楼-- · 2018-12-31 00:23

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<>

查看更多
浮光初槿花落
5楼-- · 2018-12-31 00:26

This is not how you do things in Java. There are no dynamic variables in Java. Java variables have to be declared in the source code (*). Period.

Depending on what you are trying to achieve, you should use an array, a List or a Map; e.g.

int n[] = new int[3];
for (int i = 0; i < 3; i++) {
    n[i] = 5;
}

List<Integer> n = new ArrayList<Integer>();
for (int i = 1; i < 4; i++) {
    n.add(5);
}

Map<String, Integer> n = new HashMap<String, Integer>();
for (int i = 1; i < 4; i++) {
    n.put("n" + i, 5);
}

It is possible to use reflection to dynamically refer to variables that have been declared in the source code. However, this only works for variables that are class members (i.e. static and instance fields). It doesn't work for local variables. See @fyr's "quick and dirty" example.

However doing this kind of thing unnecessarily in Java is a bad idea. It is inefficient, the code is more complicated, and since you are relying on runtime checking it is more fragile.

And this is not "variables with dynamic names". It is better described dynamic access to variables with static names.


* - That statement is slightly inaccurate. If you use BCEL or ASM, you can "declare" the variables in the bytecode file. But don't do it! That way lies madness!

查看更多
ら面具成の殇う
6楼-- · 2018-12-31 00:26

You don't. The closest thing you can do is working with Maps to simulate it, or defining your own Objects to deal with.

查看更多
无与为乐者.
7楼-- · 2018-12-31 00:30

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;
}
查看更多
登录 后发表回答