How to return multiple objects from a Java method?

前端 未结 25 3076
眼角桃花
眼角桃花 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:26

    This is not exactly answering the question, but since every of the solution given here has some drawbacks, I suggest to try to refactor your code a little bit so you need to return only one value.

    Case one.

    You need something inside as well as outside of your method. Why not calculate it outside and pass it to the method?

    Instead of:

    [thingA, thingB] = createThings(...);  // just a conceptual syntax of method returning two values, not valid in Java
    

    Try:

    thingA = createThingA(...);
    thingB = createThingB(thingA, ...);
    

    This should cover most of your needs, since in most situations one value is created before the other and you can split creating them in two methods. The drawback is that method createThingsB has an extra parameter comparing to createThings, and possibly you are passing exactly the same list of parameters twice to different methods.


    Case two.

    Most obvious solution ever and a simplified version of case one. It's not always possible, but maybe both of the values can be created independently of each other?

    Instead of:

    [thingA, thingB] = createThings(...);  // see above
    

    Try:

    thingA = createThingA(...);
    thingB = createThingB(...);
    

    To make it more useful, these two methods can share some common logic:

    public ThingA createThingA(...) {
        doCommonThings(); // common logic
        // create thing A
    }
    public ThingB createThingB(...) {
        doCommonThings(); // common logic
        // create thing B
    }
    

提交回复
热议问题