Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return two or more objects in one method?

Tags:

java

Lets say you want a method to return both a generated object and a boolean indicating the success or failure of doing so.

In some languages, like C, you might have a function return additional objects by having reference parameters, but you cannot do this in Java since Java is "pass-by-value", so how do you return several objects in Java?

like image 519
user496949 Avatar asked Mar 04 '11 02:03

user496949


2 Answers

You could do

class Result{

    Result(boolean result, Object value)
    {
        this.result = result;
        this.value = value;
    }

    public boolean getResult()
    { 
         return result; 
    }


    public Object getValue()
    { 
       result value; 
    }
    private boolean result;
    private Object value;

}

and have your function return an instance of Result

private Result myMethod()
{
   boolean result = doStuff();
   Object value = getValue();
   return new Result(result, value)
}
like image 176
Bala R Avatar answered Nov 02 '22 23:11

Bala R


I would suggest one of two things, either return null and check for it wherever you need that object, or throw an exception in the event of an error.

On success just return the object.

like image 27
Gunnar Hoffman Avatar answered Nov 03 '22 00:11

Gunnar Hoffman