JAVA:等效指针 [英] JAVA: pointers equivalent

查看:69
本文介绍了JAVA:等效指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道指针不像在C语言中那样存在,但是我想知道这样的事情是否可能实现:

I know pointers don't exist the way they do in C, but I was wondering if something like this would be possible:

我有5个全局变量r1 r2 r3 r4 r5,每个全局变量最初都初始化为null

I have 5 global variables, r1 r2 r3 r4 r5, each initially initialized to null

我想(1)找到尚未使用的变量,(2)给它分配一些东西,然后(3)稍后在程序中操纵该变量.但是,直到代码执行,我才知道变量的状态.为了弥补这一点,我现在有一堆if-else语句:

I want to (1) find the variable that hasn't already been used, (2) assign something to it, and then (3) manipulate that variable later in the program. However, I don't know the status of the variables until code execution. To make up for this, I now have a bunch of if-else statements:

if(r1==null)
    r1 = [something]    
else if(r2==null)
    r2 = [something]
else if(r3==null)
    r3 = [something]
else if(r4==null)
    r4 = [something]
else if(r5==null)
    r5 = [something]

到目前为止,一切都很好.但是问题是,我想使用在上面的代码中修改过的变量,然后在程序中稍后使用/修改该变量.

So far so good. But the problem is, I want to take the variable that was modified in the above code and use/modify that variable later in the program.

所以说,如果r1r2不为空,并且r3为空,则为r3 = [something].我想稍后在程序中修改r3.在C/C ++中,我认为我可以在if-else语句中设置指向r3的指针.然后,我可以稍后在程序中通过该指针修改r3.

So say if r1 and r2 were NOT null, and r3 was null, r3 = [something]. I want to modify r3 later on in the program. In C/C++, I'm thinking I could have set up a pointer to r3 in the if-else statement. Then I could just modify r3 through that pointer later in the program.

在Java中这可能吗?谢谢!

Is this possible in Java? Thanks!

忘记提了,r1-r5是字符串.

推荐答案

对于这种简单的操作,可以使用数组. 您可以保留数组索引作为所需变量的指针.

For something this simple, you could use an array. You can keep an array index as pointer to the variable you want.

String[] r = new String[5]; // all nulls

等等:

private int findFirstNull(String[] array) {
  for(int i=0; i<r.length; i++)
    if(r[i] == null)
      return i;
  return -1;
}

这篇关于JAVA:等效指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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