Passing Reference As Parameter In Android
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
Solution 1:
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:
voidfindsum( int no1, int no2, int[] sum ){
sum[0] = no1 + no2;
}
Anyway, I strongly suggest you to refactor your code to be more object oriented, for example:
classSumOperation {
privateintvalue;
publicSumOperation(int no1, int no2) {
this.value = no1 + no2;
}
publicintgetReturnValue() { returnthis.value; }
}
Solution 2:
There is no pass by reference in Java.
Solution 3:
This is how I solved this problem:
// By using a wrapper class.// This also works with Class objects.classIntReturn {
publicint val;
}
// For example:classStringReturn {
public String val;
}
classMain {
publicstaticvoidmain(){
IntReturniRtn=newIntReturn();
if(tryAdd(2, 3, iRtn)){
System.out.println("tryAdd(2, 3): " + iRtn.val);
}
}
publicstaticbooleantryAdd(finalint a, finalint b, final IntReturn iRtn){
iRtn.val = a + b;
returntrue; // Just something to use return
}
}
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.
Post a Comment for "Passing Reference As Parameter In Android"