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 = 5;

}

How can I achieve this in 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 n = new ArrayList();

for (int i = 1; i < 4; i++) {

n.add(5);

}

Map n = new HashMap();

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!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值