Hatefiend Hatefiend - 1 year ago 75
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;
System.out.println(x + "," + y);

In which I want to print:


I thought
, or
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 Source

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)


Or, you could use an int[] like

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

for the same output.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download