How to return multiple objects from a Java method?

前端 未结 25 3081
眼角桃花
眼角桃花 2020-11-21 23:55

I want to return two objects from a Java method and was wondering what could be a good way of doing so?

The possible ways I can think of are: return a HashMap<

25条回答
  •  名媛妹妹
    2020-11-22 00:34

    Why not create a WhateverFunctionResult object that contains your results, and the logic required to parse these results, iterate over then etc. It seems to me that either:

    1. These results objects are intimately tied together/related and belong together, or:
    2. they are unrelated, in which case your function isn't well defined in terms of what it's trying to do (i.e. doing two different things)

    I see this sort of issue crop up again and again. Don't be afraid to create your own container/result classes that contain the data and the associated functionality to handle this. If you simply pass the stuff around in a HashMap or similar, then your clients have to pull this map apart and grok the contents each time they want to use the results.

提交回复
热议问题