A brief analysis of the Integer parameter transfer in Java
- 2020-04-01 02:17:35
- OfStack
Java itself is a value-passing call, passing an address value to an object. Re - assign the address value is equal to re - point, does not affect the outer layer.
And there's something special about the Integer object. The implementation may be similar
class Integer{
final int value; //Once assigned, it cannot be changed.
}
This is what happens: The address value passed on the call cannot be changed and the outer + object itself cannot be changed. This value cannot be changed
There are many solutions
1.
The Java style is to return a value for a single value. Return the I; Outside again I = foo (); The assignment; Multiple values using arrays or objects.
2,
Pass your own wrapper class. The class MutableInteger {int value; }
3,
Pass the dedicated AtomicInteger AtomicInteger object
public static void main(String[] parameter ) {
AtomicInteger i=new AtomicInteger(40);
i.intValue();
System.out.println(i);
}
public static void change(AtomicInteger i) {
i.set(55);
}
You can also change the value after passing,
Recommend plan 1 and avoid it