How to return multiple objects from a Java method?

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

    In the event the method you're calling is private, or called from one location, try

    return new Object[]{value1, value2};
    

    The caller looks like:

    Object[] temp=myMethod(parameters);
    Type1 value1=(Type1)temp[0];  //For code clarity: temp[0] is not descriptive
    Type2 value2=(Type2)temp[1];
    

    The Pair example by David Hanak has no syntactic benefit, and is limited to two values.

    return new Pair(value1, value2);
    

    And the caller looks like:

    Pair temp=myMethod(parameters);
    Type1 value1=temp.a;  //For code clarity: temp.a is not descriptive
    Type2 value2=temp.b;
    

提交回复
热议问题