I create an Integer variable in one class and pass it to another class. How can I change the value of this variable in another class without changing the link?

For example, if the passed reference is Integer z , and I change it: for example, Integer z = 5; . It turns out that this is a new reference for z ; nothing has changed for the old variable.

  • one
    There is a suspicion that you still want to do something else, just do not understand how. What you are asking is possible, as described below, but this is a direct shot to your head. You can not do that. - Alexander Martyntsev

2 answers 2

If you do not bother - you can answer in any way , however, it is not. The fact is that Integer is a reference type and its contents can really be changed by the passed reference. The value is stored in the value field of the class Integer, but it has final private modifiers. But this will not prevent if you want to refer to it through reflection and change the value. Something like this:

 private static void change(Integer i, Integer newValue) { try { Field valueField = Integer.class.getDeclaredField("value"); valueField.setAccessible(true); valueField.setInt(i, newValue); } catch (Exception e) { e.printStackTrace(); } } 

The only question is, is it worth it?

    With Integer without reflection in any way. If you still need to turn this AtomicInteger , you can use the AtomicInteger and the set method