所以我目前的代码是:
int x = 5;
int[] one = new int[1];
one[0] = x;
int[] two = new int[1];
two[0] = x;
x = 10;
System.out.println(one[0]);
System.out.println(two[0]);
这里的目标是获得两个10的输出。相反,我得到的是两个5被打印。
我知道在C ++中有一种说& x来引用引用类型的方法但是我不知道Java中有类似内容吗?
如果有人能帮助我,我真的很感激。
修改
干杯队员。我最终创建了自己的课程并使用了它。
class Ideone {
public static void main (String[] args) throws java.lang.Exception
{
MyTester x = new MyTester();
x.i = 5;
MyTester[] one = new MyTester[1];
one[0] = x;
MyTester[] two = new MyTester[1];
two[0] = x;
x.i = 10;
System.out.println(one[0].i);
System.out.println(two[0].i);
}
}
class MyTester
{
public MyTester() {}
public int i;
}
答案 0 :(得分:0)
不,没有办法。您可以做的最接近的事情是one = two
,然后one[0] = 10
,然后two
将指向与one
相同的数组,并反映更改。
尽管如此,你不能仅使用裸基元来做这样的事情。
答案 1 :(得分:0)
它不能按预期工作,因为它是按值调用的。 有一篇很好的旧文章,有许多好的例子可供阅读:Is Java "pass-by-reference" or "pass-by-value"?