在android中将引用作为参数传递
我是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;
}
请建议我一个解决方案,
谢谢
I am newbie in java/android. I am a c/c++ developer. May i know how to pass a reference as parameter in android. An illustrative c sample code shown below
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;
}
please suggest me a solution
thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您不能在 Java 中传递 int 作为引用。
int
是主要类型,它只能按值传递。如果您仍然需要传递 int 变量作为引用,您可以将其包装在可变类中,例如 int 数组:
无论如何,我强烈建议您重构代码以更加面向对象,例如:
You cannot pass an int as reference in Java.
int
is a primary type, it can be passed only by value.If you still need to pass an int variable as reference you can wrap it in a mutable class, for example an int array:
Anyway, I strongly suggest you to refactor your code to be more object oriented, for example:
Java 中没有引用传递。
There is no pass by reference in Java.
这就是我解决这个问题的方法:
我有一个用于此目的的此类类型的个人库。 Lambda 是这些类的另一个原因,因为您需要一个“最终”变量才能从 Lambda 中获取值,而不是通过 return 语句。
更新:
我已经替换了所有特定的包装类
使用单个泛型类:
以下是它的使用方法:
这似乎是多余的,因为我拥有所有以前开发的包装器类。然而,现在我只有一个可以容纳任何东西的泛型类!
This is how I solved this problem:
I have a personal library of these types of classes for this purpose. Lambdas are another reason for these classes, as you need to have a 'final' variable to get a value out of a Lambda, other than by return statement.
Update:
I have replaced all of my specific wrapper classes
with a single Generic class:
Here is how it can be used:
It may seem as though this would be redundant since I had all of the previously developed wrapper classes. However, now I have only one generic class that can hold anything!