开发者

Pointer deferencing and manipulating objects which are being pointed to - equivalent constructs in Java

开发者 https://www.devze.com 2023-01-22 08:14 出处:网络
Hello In C++ you can do the following: int x = 5 cout << x; // prints 5 int* px = &x; (*px)++; cout <<x;

Hello

In C++ you can do the following:

int x = 5

cout << x;
// prints 5

int* px = &x;

(*px)++;
cout <<x;
// p开发者_运维技巧rints 6

Is there an equivalent construct in Java


In order to do this, you have to create an object that contains an int. Then, you can pass around a reference to that object, and you can increment the int that's in that object. But there's no way that you can have another reference to the same int and increments in one will increment the other -- unless both cases are references to the same wrapper object.


The answer is "sort of". As long as you're dealing with primitives, just wrap the value in an array.

int[] a = {5};
int[] b = a;
b[0]++;
System.out.println(a[0]);

As others have pointed out, for more complex problems, your best bet is always to create an object with an 'increment' or 'set' method that modifies a stored value.


Not as such.

You can think of Java as passing everything by reference, so

Foo f1 = new Foo();
Foo f2 = f1;

means f2 and f1 point to the same object (unlike C++ where the assignment would make a copy). Equivalent C++ code would make f2 a Foo&.

Java will autobox ints to Integers, but Integers are immutable. So you need to either write your own MutableInteger, or use something like the java.util.AtomicInteger if you want to pass by reference and change values as a side effect (which I suspect is your underlying motive).

Sadly you can't override operators in Java so the syntax will be more verbose then equivalent C++ code.


No... Java abstracts away the concept of pointers and memory locations. Pointers, and pointer dereferencing are not possible in Java.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号