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:
- pass an array as parameter
- pass a wrapper as parameter
- return a pair
- return a wrapper containing error number and result
- throw exception
- 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!
There’s a MutableInt component in the Apache Commons library. Since it’s mutable, you can pass it by reference.