简体   繁体   English

是否可以使用Java中的变量来命名变量?

[英]Is it possible to name a variable using a variable in Java?

What I would like to do is have a loop that names a certain number of variables each time. 我想做的是有一个循环,每次都命名一定数量的变量。 So sometimes when I run the program, this loop will create say 3 variables a1, a2 & a3 but other times it could name more, eg (if this sort of thing were possible): 因此,有时在我运行程序时,此循环将创建3个变量a1,a2和a3,但有时它可以命名更多,例如(如果可能的话):

for(int i=1; i<=n;i++) {
    int ai = i;
}

So in the case (for i=1) the name of the int would be a1 and contains the int 1. This clearly won't work, but I was wondering if there was a way to achieve this effect -- or should I stop hacking and use a different data structure? 因此,在(for i=1)的情况下(for i=1) int的名称将为a1并包含int1。这显然行不通,但我想知道是否有办法实现这种效果-还是应该停止入侵并使用不同的数据结构?

Thanks. 谢谢。

Also, this is just an example. 另外,这仅是示例。 I'm using it to create arrays. 我正在用它来创建数组。

No, this is not possible. 不,这是不可能的。 Java has no way to construct symbols. Java无法构造符号。 However, you can use it to define variable-size arrays. 但是,您可以使用它来定义可变大小的数组。 For example: 例如:

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

Which seems like what you may want. 这似乎是您可能想要的。

Map

Can you use an implementation of Map such as a HashMap ? 您可以使用Map的实现,例如HashMap吗?

import java.util.HashMap;
import java.util.Map;


public class test {

    public static void main(String[] args) {

        //Fill your map structure
        Map<String, Integer> theMap = new HashMap<String, Integer>();
        for(int i = 1; i <= 100; i++) {

            theMap.put("a" + i, i);
        }

        //After this you can access to all your values
        System.out.println("a55 value: " + theMap.get("a55"));
    }
}

Program output: 程序输出:

a55 value: 55

Rather than trying to define variables a1, a2, a3, ... you can simply define a fixed size array: 不必尝试定义变量a1,a2,a3,...,您只需定义一个固定大小的数组即可:

int[] anArray = new int[10]; 

and refer to a[1], a[2], a[3],... 并参考a [1],a [2],a [3],...

我只是制作一个数组数组,其中索引等于i值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM