Hatefiend Hatefiend - 2 months ago 6
Java Question

Java - Pointer to integer type

I want to have a pointer to an Integer type, without making a custom class that has an element which is an integer.

My desired effect:

Byte x = 5; // Byte is just an example and WILL NOT work.
Byte y = x;
y--;
System.out.println(x + "," + y);


In which I want to print:

4,4


I thought
Byte
,
Integer
, or
Double
might be able to do this because they are sort of classes with an inner variable which is a primitive type but they don't keep references to the object that they are assigned to.

Answer

You can't use a primitive wrapper type, because those are immutable. You could use an AtomicInteger to do this. Something like,

AtomicInteger x = new AtomicInteger(5);
AtomicInteger y = x;
System.out.println(y.decrementAndGet() + "," + x.get());

Outputs (as requested)

4,4

Or, you could use an int[] like

int[] x = { 5 };
int[] y = x;
System.out.println(--x[0] + "," + y[0]);

for the same output.

Comments