Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to return multiple Integer in java?

Tags:

java

reference

i have a method which will return an error code(int) and a result(int). If the error code is 0, the result is valid. In c++, this may like:

int method(int& result);

Java calls by reference, so if we change a object in a method, the change is visible by the caller. But, int is not a class, so I could't make is like this in java:

int method(int result);

And Integer and Long are immutable in Java, so change is not visible by the caller if i do it like this:

Integer method(Integer result);

Wrap the result into a Wrapper Class works! But, that's no so simple!

I work with c++ for long and move to java recently, this bother me a lot! could any one provide a solution?

=================================

well, in a conclusion, there are these flowing solutions:

  1. pass an array as parameter
  2. pass a wrapper as parameter
  3. return a pair
  4. return a wrapper containing error number and result
  5. throw exception
  6. pass a mutableint

1st and 2nd make my api ugly 3rd and 4th seems not so perfect about 5th, this method is frequantly called so i've to take efficiency into consideration 6th seems match my require most

thanks!

like image 677
qiuxiafei Avatar asked Jan 11 '12 13:01

qiuxiafei


2 Answers

Don't use return codes for errorcodes: use Exceptions; it is what they are for. Just return the actual result.

like image 183
Mark Rotteveel Avatar answered Oct 01 '22 02:10

Mark Rotteveel


You can't return more than one integer for your method. What you can do is:

  • Create a new object with 2 integer fields and let your method return an instance of that object (basically a wrapper);

  • Make your method return an array of 2 integers (or take it as a parameter);

  • Make your method return a String variable of the form <int 1>,<int 2>. You can then use the split() to get the numbers from the string and parse them back to integers.

  • Make your method throw the exception and return the number.

like image 42
npinti Avatar answered Oct 01 '22 01:10

npinti