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

查看:563
本文介绍了在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变量。期间。

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

可以使用反射动态引用已在源代码中声明的变量。但是, only 适用于类成员的变量(即静态和实例字段)。它不适用于局部变量。请参阅@ 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 dynamic access to variables with static names.

* - 该语句稍微不准确。如果使用BCEL或ASM,则可以声明字节码文件中的变量。但是不要这样做!那种方式就是疯狂!

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

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