在Java的引用传递? [英] Pass by reference in java?

查看:116
本文介绍了在Java的引用传递?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图建立Android GSMS痘痘GAM。我哈瓦很多单位和所有的人都目的地。要计算我使用了一个名为的Caldes功能目标。此功能的的Caldes 是我的计算单位的速度。所以,我要送一些变量到我所编辑和再次使用他们。为此,我必须参照发送这些变量。下面是一个简单的C ++如何做到这一点在Java中?

 无效掉期(SO​​METYPE&安培; ARG1,SOMETYPE&安培; ARG2){
    SOMETYPE TEMP = ARG1;
    ARG1 = ARG2;
    ARG2 =温度;
}
...
SOMETYPE VAR1 = ...; //值A
SOMETYPE VAR2 = ...; //值B
掉期(VAR1,VAR2); //交换它们的值!


解决方案

Java没有通通过引用的。你有两个选择:


  1. 传递数据数组:

     无效掉期(SO​​METYPE []参数){
        SOMETYPE TEMP = ARGS [0];
        ARGS [0] = ARGS [1];
        ARGS [1] =温度;
    }

    ...但使用它是在调用code一痛:

      SOMETYPE一​​个= ...;
    SOMETYPE B = ...;
    SOMETYPE [] ARGS =新SOMETYPE [] {A,B};
    掉期(参数);
    一个= ARGS [0];
    B = ARGS [1];


  2. 创建具有公共 SOMETYPE 成员一个对象,并传递对象引用。

     无效掉期(SomeTypeContainer C){
        SOMETYPE TEMP = C.A;
        C.A = C.B;
        C.B =温度;
    }

    这是非常相似,#1,但可能更方便与调用code的工作。

      SomeTypeContainer C =新SomeTypeContainer(/ * ...的东西,创造a和b ... * /);
    //使用C.A和C.B直接
    掉期(C);
    //使用C.A和C.B直接,他们现在换


I'm trying to build a litle gam for android GSMs. I hava lots of units and all of them have destinations. To calculate destination I'm using a function called CalDes. This function CalDes is calculating my unit's speed. So I'm sending some variables into which I have to edit and use em again. For this I have to send these variables with reference. Here is a simple for C++ How to do that in java?

void swap(SomeType& arg1, Sometype& arg2) {
    SomeType temp = arg1;
    arg1 = arg2;
    arg2 = temp;
}
...
SomeType var1 = ...; // value "A"
SomeType var2 = ...; // value "B"
swap(var1, var2); // swaps their values!

解决方案

Java doesn't have pass-by-reference at all. You have a couple of options:

  1. Pass the data in an array:

    void swap(SomeType[] args) {
        SomeType temp = args[0];
        args[0] = args[1];
        args[1] = temp;
    }
    

    ...but using it is a pain in the calling code:

    SomeType a = ...;
    SomeType b = ...;
    SomeType[] args = new SomeType[] { a, b };
    swap(args);
    a = args[0];
    b = args[1];
    

  2. Create an object that has public SomeType members, and pass in the object reference.

    void swap(SomeTypeContainer c) {
        SomeType temp = c.a;
        c.a = c.b;
        c.b = temp;
    }
    

    Which is very similar to #1, but probably more convenient to work with from calling code.

    SomeTypeContainer c = new SomeTypeContainer(/* ... something that creates a and b ... */);
    // Use c.a and c.b directly
    swap(c);
    // Use c.a and c.b directly, they're now swapped
    

这篇关于在Java的引用传递?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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