Here’s a java tip I discovered.
Java doesn’t allow functions to return multiple parameters. You can’t pass by reference like in C/C++.
Say you have this function in C or C++:
int get(int a, int* b, int* c)
{
*b = 2 * a;
*c = 3 * a;
return 4 * a;
}
Now you want to write that function in Java. One option is to create an object which stores 3 integer values and return that.
An option involving less work, is the following:
Java lets you pass in an object, to which you can modify the content of the object, so:
First create a java class which stores an integer:
public class _Integer
{
public int _integer;
public _Integer
{
}
}
Now pass this object to your java function whenever you need to return more than one value:
int a = 1;
_Integer bInteger = new _Integer();
_Integer cInteger = new _Integer();
int d = get(a, bInteger, cInteger);
int get(int a, _Integer b, _Integer c)
{
b._integer = 2 * a;
c._integer = 3 * a;
return 4 * a;
}
If you need to pass doubles, create a _Double class, etc.
I thought that was a pretty cool workaround I came up with and just wanted to share.:)
Leave a Reply
You must be logged in to post a comment.