0

如何将一个对象或变量的地址存储在 Java 中的另一个对象中。就像我们在 C++ 中所做的那样

int a=&b; // b 也是 int

如果我想在 Java 中通过引用将引用类型对象传递给任何方法,我该怎么做,因为默认情况下它们是按值传递的。

4

3 回答 3

5

You can't, basically. Everything is passed by value in Java, and there's no way of changing that.

The closest you can come is to create your own generic mutable wrapper type, or use an array of length 1. The wrapper approach makes it much clearer what you're doing, but it's less efficient. You can use AtomicReference<V> as a wrapper type if you want, although its use implies that you're concerned about concurrency when you probably aren't.

For wrappers of primitive types, you could either use the Integer, Long etc classes, or you could write an individual specific wrapper type for each primitive. (Again, the latter would be slightly more efficient.)

Fundamentally though, you should try to design your code not to need this. I very rarely find it a useful technique. If you find yourself wanting to do it very often, you may be "thinking" in a different language...

于 2012-07-03T06:25:30.103 回答
0

You can not use addresses in Java. There is simply no such ability. All things are passed by value. When you want to pass an object to be mutated you have several ways:

a) Pass an array:

int [] valueArray = new int[1];
valueArray[0] = <your value>;

b) Pass a mutable wrapper, which you shoud write by your self.

c) Pass an input int and retur a new value:

int a = 5;
a = sqr(a);
于 2012-07-03T06:27:38.293 回答
0

从 C++ 到 java 是有区别的。尽管在 java 中使用 Object 的地址不是一个好习惯,但有一些方法可以获取逻辑地址。

http://javapapers.com/core-java/address-of-a-java-object/

我希望这能帮到您。

于 2012-07-03T06:54:17.800 回答