How to return multiple objects from a Java method?

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

    I have a been using a very basic approach to deal with problems of multiple returns. It serves the purpose, and avoids complexity.

    I call it the string separator Approach

    And it is effective as it can even return values of Multiple Types e.g. int,double,char,string etc

    In this approach we make a use of a string that is very unlikely to occur generally. We call it as a separator. This separator would be used to separate various values when used in a function

    For example we will have our final return as (for example) intValue separator doubleValue separator... And Then using this string we will retrieve all the information required, that can be of diffrent types as well

    Following code will Show the working of this concept

    The separator used is !@# and 3 values are being returned intVal,doubleVal and stringVal

            public class TestMultipleReturns {
    
                public static String multipleVals() {
    
                    String result = "";
                    String separator = "!@#";
    
    
                    int intVal = 5;
                    // Code to process intVal
    
                    double doubleVal = 3.14;
                    // Code to process doubleVal
    
                    String stringVal = "hello";
                    // Code to process Int intVal
    
                    result = intVal + separator + doubleVal + separator + stringVal + separator;
                    return (result);
                }
    
                public static void main(String[] args) {
    
                    String res = multipleVals();
    
                    int intVal = Integer.parseInt(res.split("!@#")[0]);
                    // Code to process intVal
    
                    double doubleVal = Double.parseDouble(res.split("!@#")[1]);
                    // Code to process doubleVal
    
                    String stringVal = res.split("!@#")[2];
    
                    System.out.println(intVal+"\n"+doubleVal+"\n"+stringVal);
                }
            }
    

    OUTPUT

    5
    3.14
    hello
    BUILD SUCCESSFUL (total time: 2 seconds)
    

提交回复
热议问题