Linked by Bjorn Raupach on Thu 17th Jul 2008 06:01 UTC
Java Today was one of those days when I wished Java would support multiple return values. I had to develop a rather CPU-intensive algorithm which would compute a solution for a knotty constraint problem. Having a solution alone is sometimes not enough and you also need to add some parameters which measure the quality of the computed outcome. Most of these accompanying parameters can or have to be computed within the algorithm itself, but Java allows you to return only one value either an object or a primitive type. People working with Lisp, MATLAB or Perl, just to mention a few, don't have a problem like this at all. Functions supporting multiple return values is already implemented at the language level and frameworks make heavy use of this. But as a Java programmer you are pretty much stuck here and need to consider some other means to come out of this situation. In the following I would like to give some hints on that topic. Hopefully they are of help for anyone having the same problem every now and then.
Thread beginning with comment 323492
To view parent comment, click here.
To read all comments associated with this story, please click here.
FunkyELF
Member since:
2006-07-26

My first thought in C++ would be to have a templated ReturnTriple struct along the lines of:

template
struct ReturnTriple
{
A first;
B second;
C third;
};

which is cheap, type-safe and reusable.

The first poster on here gave a nice link for javatuple which does something very similar. I just looked and it seems real nice. it has classes for Single, Pair, Triple etc. up to Decuple.
I'm not sure if your C++ example retains type safety but this javatuple package does.


EDIT: Or, as another poster pointed out, just pass parameters by reference. Is this not possible in Java?


Java has Objects and primitives (because back in the day people were bitching about performance). Primitives are pass by value, Objects are passed as a reference. This means that if you pass a Vector to a method, because it is an Object, if you add or remove from that Vector in the method the changes will be visible after the method is called. However, even though Integer is a class, there are no methods to change the value of one. So, a method that needs to return two integers could return a List<Integer> or an Integer[], but things get ugly when you need to return an Integer and a String.

Reply Parent Score: 2