-1

I Know that in Java, Integer is an immutable object. but I need a way to be able to change an integer in a method and see the change outside the method. For example:

int getInt(){
    int my_int=0;
    test(my_int);
}

void test(int i){
    i=3;
}

What I want to see as the output of getInt is 3 not 0. Is there any way to do that?

my method is more complicated than what I wrote, and it will return another object. That's why I want to change the int in the input and not return it.

Alex
  • 573
  • 1
  • 10
  • 23
  • may be this will help http://stackoverflow.com/a/40523/3981536 – Jos Jun 03 '16 at 19:57
  • Another option to those given already: You could have a member variable within the class instead of a local variable in the method. This one could be accessed from anywhere necessary and you do not have to bother with passing it around. I admit, this somehow spoils the rest of the class, so I would rather prefer an alternative - *unless* there is no such rest, as the only purpose of the class is doing the calculation (and it is possibly even discarded afterwards). Then I would consider this a valid approach. – Aconcagua Jun 03 '16 at 20:19

2 Answers2

0

You simply can't. You need to wrap it into a container object which is able to change its content. Eg:

class IntWrapper {
  private int value;
  ..
}

Or you can return a new value and assign the result to it, eg

int x = 10;
x = foo(x);

which is basically equivalent to your example.

Jack
  • 131,802
  • 30
  • 241
  • 343
  • Thanks my method is more complicated than what I wrote, and it will return another object. That's why I want to change the int in the input. – Alex Jun 03 '16 at 19:59
0

It is not possible if the argument has to be an int primitive. You can use an AtomicReference<Integer>

AtomicReference<Integer> iRef = new AtomicReference<>(0);
test(iRef);

void test(AtomicReference<Integer> ref) {
  ref.set(3);
}

This is honestly kind of an anti-pattern - it's often not super clear from looking at the method signature what's going to happen to your values. It'd be clearer to have test return an int, and then have something like i = test(i);.

Andrew Rueckert
  • 4,858
  • 1
  • 33
  • 44