How to implement int in/out params in java

前端 未结 6 2088

Apologies for asking such a primitive question.

I wrote a function which took one parameter; this parameter was supposed to be an in/out parameter.

After d

6条回答
  •  一整个雨季
    2020-12-21 12:37

    Question 1:

    You could pass an array of 1 int, and change the unique element value, or pass a mutable integer wrapper object (like AtomicInteger, for example). Or, instead of using in/out parameters, your method could return an object containing a boolean field and an integer field.

    Question 2:

    currentFoo = currentFoo + 1
    

    is the same as:

    int tmp = currentFoo.intValue(); // auto-unboxing
    tmp = tmp + 1;
    currentFoo = Integer.valueOf(tmp); // auto-boxing
    

    A new Integer instance is thus assigned to currentFoo. The original instance (being immutable) is not modified.

    All parameters are passed by value in Java. When using objects, the reference to the object is passed, and it's passed by value: a copy of the reference is made and passed to the method. If you assign something to the passed reference, you assign it to a copy, and the original reference is thus still pointing to the original object.

提交回复
热议问题