How to return multiple objects from a Java method?

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

    Keep it simple and create a class for multiple result situation. This example accepts an ArrayList and a message text from a databasehelper getInfo.

    Where you call the routine that returns multiple values you code:

    multResult res = mydb.getInfo(); 
    

    In the routine getInfo you code:

    ArrayList list= new ArrayList();
    add values to the list...
    return new multResult("the message", list);
    

    and define a class multResult with:

    public class multResult {
        public String message; // or create a getter if you don't like public
        public ArrayList list;
        multResult(String m, ArrayList l){
            message = m;
            list= l;
    }
    

    }

提交回复
热议问题