在 Java 中使用动态名称分配变量 [英] Assigning variables with dynamic names in Java

查看:33
本文介绍了在 Java 中使用动态名称分配变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在java中分配一组变量如下:

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

如何在 Java 中实现这一点?

How can I achieve this in Java?

推荐答案

这不是您在 Java 中做事的方式.Java 中没有动态变量.Java 变量必须在源代码中声明1.

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

根据您要实现的目标,您应该使用数组、ListMap;例如

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

<小时>

可以使用反射动态引用源代码中声明的变量.但是,这适用于作为类成员的变量(即静态和实例字段).它不适用于局部变量.参见@fyr 的快速而肮脏"的例子.


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.

然而,在 Java 中做这种不必要的事情是一个坏主意.它效率低下,代码更复杂,而且由于您依赖于运行时检查,因此它更脆弱.这不是具有动态名称的变量".最好将其描述为对具有静态名称的变量的动态访问.

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 as dynamic access to variables with static names.

1 - 这个说法有点不准确.如果您使用 BCEL 或 ASM,您可以声明"字节码文件中的变量.但是不要这样做!那样就疯了!

这篇关于在 Java 中使用动态名称分配变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆