在android中传递引用作为参数

Ris*_*han 3 java android pass-by-reference

我是java/android的新手.我是ac/c ++开发人员.我可以知道如何在android中传递引用作为参数.示例c示例代码如下所示

void main()
{
  int no1 = 3, no2 = 2, sum = 0;
  findsum( no1, no2, sum );
  printf("sum=%d", sum );
}

void findsum( int no1, int no2, int& sum )
{
  sum = no1 + no2;
}
Run Code Online (Sandbox Code Playgroud)

请给我一个解决方案

谢谢

ono*_*nof 7

您不能在Java中传递int作为引用.int是主要类型,它只能通过值传递.

如果你仍然需要传递一个int变量作为引用,你可以将它包装在一个可变类中,例如一个int数组:

void findsum( int no1, int no2, int[] sum )
{
  sum[0] = no1 + no2;
}
Run Code Online (Sandbox Code Playgroud)

无论如何,我强烈建议您重构代码以使其更加面向对象,例如:

class SumOperation {
   private int value;

   public SumOperation(int no1, int no2) {
      this.value = no1 + no2;
   }

   public int getReturnValue() { return this.value; }
}
Run Code Online (Sandbox Code Playgroud)