Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best way to return a pair of values in Java? [duplicate]

This is a small issue, as I could easily whip up a pair class to do the job. I don't really want to do this though, and I feel like there should be some simple, built-in, java-like way of returning two values. What do you guys is the best, simplest way of doing this? Arrays? Some other data structure?

like image 999
Graham Avatar asked Jun 07 '11 21:06

Graham


People also ask

Can you return 2 values in Java?

You can return only one value in Java. If needed you can return multiple values using array or an object.


1 Answers

As far as I know, there is unfortunately no built-in representation of a pair in Java (and I certainly wish there was). Personally, when I code a project where I find that a pair class often would be useful, I create a generic Pair<T, U> class (which is probably what you were thinking of). Returning an array is a fast and simple way, but you might come to regret it later, because people who use your method will wonder whether the method might at some point return more than two values.

Whichever solution you choose: whenever you feel that you need a Pair, you should consider whether the time saved today by using e.g. a generic Pair class really is worth the loss of information to the next person who reads the code (and that person may well be you in six months). Writing a separate class for the return type takes more time now, but it would convey more information to those that use your method (namely, it tells the users what the return value represents, and contains useful member names for the two values). If it is a non-public method that is used only a few places, though, a Pair is more acceptable.

like image 166
Aasmund Eldhuset Avatar answered Oct 11 '22 11:10

Aasmund Eldhuset