How can I change the value of Integer when it is an argument, such as the value of an array of changes?

public static void main(String[] args) { Integer i = new Integer(0); int[] arr = {1}; p1(i); p2(arr); System.out.println(i); System.out.println(arr[0]); } public static void p1(Integer i) { i = 2; } public static void p2(int[] i) { i[0] = 2; } 

// output: 0, 2

How can I change the value of i since I am changing the value of arr?

+6
source share
4 answers

You cannot change the value of the variable i in main from method p1 , because the argument is passed by value: parameter i in p1 completely separate from i , it's just that they have the same value at the beginning of the method. Java always uses pass-by-value semantics, but when a parameter type is a class, it refers to a value.

In fact, you do not change the value of arr , either - this is a reference to the same array as before, but the value in the array has been changed. And this is what you cannot do with Integer , because Integer is an immutable type.

If you need a mutable class like Integer , you can use AtomicInteger :

 public static void main(String[] args) { AtomicInteger i = new AtomicInteger(0); modify(i); System.out.println(i); } private static void modify(AtomicInteger x) { x.set(2); } 

I usually did not do this, however, I usually try not to change the objects referenced by the method parameters. Instead, I write methods that compute a single result and return it.

+13
source

Simply put: you cannot, because Integer immutable, and you only get the address of the object by value, so replacing the entire object is impossible, because after the method is completed, the old object is reassigned.

+3
source

Only using some hacks. You can do it as follows:

 public static void p1(Integer curInt) { Field field = curInt.getClass().getDeclaredField("value"); // Integer stores the real value in private field "value" field.setAccessible(true); field.set(curInt, 2); } 
+1
source

You can use AtomicInteger , which allows you to change instead of Integer :

 public static void main(String[] args) { AtomicInteger i = new AtomicInteger(0); p1(i); System.out.println(i); } public static void p1(AtomicInteger i) { i.set(2); } 
0
source

Source: https://habr.com/ru/post/976227/


All Articles