Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return multiple values in Java

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 ;
}
like image 395
shadi Avatar asked Nov 15 '12 08:11

shadi


People also ask

Can I return multiple values in Java?

Java doesn't support multi-value returns.

How can I return multiple values?

You can return multiple values by bundling those values into a dictionary, tuple, or a list. These data types let you store multiple similar values. You can extract individual values from them in your main program. Or, you can pass multiple values and separate them with commas.


1 Answers

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) ;
like image 68
Denys Séguret Avatar answered Oct 07 '22 11:10

Denys Séguret