How to return multiple objects from a Java method?

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

    You can utilize a HashMap as follows

    public HashMap yourMethod()
    {
    
       .... different logic here 
    
      HashMap returnHashMap = new HashMap();
      returnHashMap.put("objectA", objectAValue);
      returnHashMap.put("myString", myStringValue);
      returnHashMap.put("myBoolean", myBooleanValue);
    
      return returnHashMap;
    }
    

    Then when calling the method in a different scope, you can cast each object back to its initial type:

    // call the method
    HashMap resultMap = yourMethod();
                    
    // fetch the results and cast them
    ObjectA objectA = (ObjectA) resultMap.get("objectA");
    String myString = (String) resultMap.get("myString");
    Boolean myBoolean = (Boolean) resultMap.get("myBoolean");
    

提交回复
热议问题