multiple return values : Java Glossary

multiple return values
You can pass multiple parameters to a method, how do you get multiple values back? Here are four methods:
  1. The official way is to invent a new class with fields for each value with getters and setters for each field. With a decent IDE (Integrated Development Environment) like IntelliJ Idea, this is fairly painless. You return an object of this new class from your method. Sun uses this technique with Point, Dimension and Location. If you can’t think of a good inclusive English name for this new class, then these two values are not logically related and you should not be writing a method to return multiple fields at once.
  2. the quick and dirty way, you return an array of heterogeneous objects e.g.
    The unboxing intValue() is automatic inJava version 1.5 or later.

    The two main reasons not to use this technique are:

    • You defeat compile-time type consistency checking. If you use String[] (or similar specific type) instead of Object[] the technique is not quite as disreputable. You might even pass in multiple arrays of different types, but that is getting ugly.
    • It is not at all clear from the code which data goes in which slot. Maintenance programmers will tend to change the assignment and fail to keep the documentation up to date. The code is thus almost as unreadable as machine language.
  3. Pass in an Object as a parameter, and have the callee modify that Object’s fields. You will see Sun doing this with Dimension objects, for example.
  4. Split the work up into several method calls. The first does the computation and the rest retrieve but one of the results each. You can eliminate the computation call by having the result-retriever methods check if the computation is up to date, using lazy evaluation of the results. This is how Sun’s GregorianCalendar works.

CMP homejump to top You can get the freshest copy of this page from: or possibly from your local J: drive (Java virtual drive/mindprod.com website mirror)
http://mindprod.com/jgloss/multiplereturn.html J:\mindprod\jgloss\multiplereturn.html
logofeedback Please email your feedback for publication, letters to the editor, errors, omissions, typos, formatting errors, ambiguities, unclear wording, broken/redirected link reports, suggestions to improve this page or comments to Roedy Green : feedback email If you want your message kept confidential, not considered for posting, please explicitly specify that.
mindprod.com IP:[65.110.21.43]
view BlogYour face IP:[38.107.179.210]
You are visitor number 24,200.