10

I wrote a function in Java and I want this function to return multiple values. Except use of array and structure, is there a way to return multiple values?

My code:

String query40 = "SELECT Good_Name,Quantity,Price from Tbl1 where Good_ID="+x;
Cursor c = db.rawQuery(query, null);
if (c!= null && c.moveToFirst()) 
{
  GoodNameShow = c.getString(0);
  QuantityShow = c.getLong(1);
  GoodUnitPriceShow = c.getLong(2);
  return GoodNameShow,QuantityShow ,GoodUnitPriceShow ;
}
2
  • What matters isn't "Eclipse" but the language (Java). Commented Nov 15, 2012 at 8:02
  • 2
    I realise your code is pseudo-Java, but ensure you name your variables with camelCase (e.g. goodNameShow or goodUnitPriceShow). Commented Nov 15, 2012 at 8:11

3 Answers 3

30

In Java, when you want a function to return multiple values, you must

  • embed those values in an object you return
  • or change an object that is passed to your function

In your case, you clearly need to define a class Show which could have fields name, quantity and price :

public class Show {
    private String name;
    private int price;
    // add other fields, constructor and accessors
}

then change your function to

 public  Show  test(){
      ...
      return new Show(GoodNameShow,QuantityShow ,GoodUnitPriceShow) ;
Sign up to request clarification or add additional context in comments.

3 Comments

@estiedi Do you mean that Collection.sort is bad style ? You can't make efficient code if you try to make it understandable by people who don't know the most basic facts of the language. If somebody doesn't know that a received object can be changed by a method, then he must learn before being involved in a professional team.
It's still regrettable that languages didn't learn from the CLU example. CLU's related multiple assignment is of semi-dubious use (x,y = y,x), but multiple return values is very useful (x,y = function(params)). Forcing a wrapping object to be returned (often by "clean" declarations similar to class Pair<A,B>)has a penalty under very many tight calls, and passing an object to hold return values is horribly messy with no compiler guarantee that the fields are filled.
@tgm1024 You should have a look at Go where bot returning multiple values and multiple assignements are very useful ;)
2

One quick and ugly approach I encountered a few times (even in java library itself) is to return your values as Object[] and then unpack using casting. e.g.

public Object[] myfunc() {
  String name = "...";
  Integer quantity = 5
  Float price = 3.14
  return new Object[] { name, quantity, price };

Then, it is used like this:

Object[] output = myfunc();
String name = (String) output[0];
Integer quantity = (Integer) output[1];
Float price = (Float) output[2];

Embedding the values in a dedicated object is much cleaner, but I leave it here anyway.

Comments

0

I have developed a very basic approach to deal with this kind of situation.

I have used a logic of seperator in Strings.

For example if you need to return in the same function 1. int value 2. double value 3. String value

you could use a separator string

For example ",.," this kind of string would not generally appear anywhere.

You could return a String consisting of all values separated by this separator "< int value >,.,< double value >,.,< String value >"

and convert into equivalent types where the function has been called by using String.split(separtor)[index]

Refer the following code for explanation -

separator used =",.,"

public class TestMultipleReturns{

 public static void main(String args[]){

   String result =  getMultipleValues();
   int intval = Integer.parseInt(result.split(",.,")[0]);
   double doubleval = Double.parseDouble(result.split(",.,")[1]);     
    String strval = result.split(",.,")[2];
 }

 public static String getMultipleValues(){

   int intval = 231;//some int value      
   double doubleval = 3.14;//some double val
   String strval = "hello";//some String val

   return(intval+",.,"+doubleval+",.,"+strval);

 }
}

This approach can be used as a shortcut when you do not want to increase number of classes for only function returns

It depends on situation to situation which approach to take.

3 Comments

Although this suggestion does not increase the number of classes, it is a horrible approach for many reasons: You create multiple unnecessary objects (StringBuilder, Strings) which are far more expensive than a single instance of a utility class. The effort of retrieving the values is unjustifiable large, requires unnecessary code and has a noticeable impact on the performance. As you already noticed, the separator must not appear in the string and that is usally an unjustifiable assumption.
I downvoted just so people never actually uses this approach. It's bad for performance and readability, and the calee never know what to expect from a return like that.
@still_learning - I know that this approach is very bad as far as performance is concerned, but that was just a part of practice that I had done when I had started with programming. I mostly worked on julia and matlab where you can return multiple vals like, return var1,var2 etc... So when I started off with JAVA I had just done as a part of practising. I actually thought that it would work good but then I felt later that it gives very poor performance.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.