Passing by reference in Java?

后端 未结 4 1363
Happy的楠姐
Happy的楠姐 2020-12-20 22:19

In C++, if you need to have 2 objects modified, you can pass by reference. How do you accomplish this in java? Assume the 2 objects are primitive types such as int.

4条回答
  •  失恋的感觉
    2020-12-20 23:21

    Wrap them in an object and then pass that object as a parameter to the method.

    For example, the following C++ code:

    bool divmod(double a, double b, double & dividend, double & remainder) {
      if(b == 0) return false;
      dividend = a / b;
      remainder = a % b;
      return true;
    }
    

    can be rewritten in Java as:

    class DivRem {
      double dividend;
      double remainder;
    }
    
    boolean divmod(double a, double b, DivRem c) {
      if(b == 0) return false;
      c.dividend = a / b;
      c.remainder = a % b;
      return true;
    }
    

    Although more idiomatic style in Java would be to create and return this object from the method instead of accepting it as a parameter:

    class DivRem {
      double dividend;
      double remainder;
    }
    
    DivRem divmod(double a, double b) {
      if(b == 0) throw new ArithmeticException("Divide by zero");
      DivRem c = new DivRem();
      c.dividend = a / b;
      c.remainder = a % b;
      return c;
    }
    

提交回复
热议问题