在Java中返回多个值

sha*_*adi 8 java return function

我在Java中编写了一个函数,我希望这个函数返回多个值.除了使用数组和结构,有没有办法返回多个值?

我的代码:

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 ;
}
Run Code Online (Sandbox Code Playgroud)

Den*_*ret 29

在Java中,当您希望函数返回多个值时,您必须这样做

  • 将这些值嵌入到您返回的对象中
  • 或更改传递给您的函数的对象

在您的情况下,您显然需要定义一个Show可以包含字段的类name,quantity并且price:

public class Show {
    private String name;
    private int price;
    // add other fields, constructor and accessors
}
Run Code Online (Sandbox Code Playgroud)

然后将你的功能改为

 public  Show  test(){
      ...
      return new Show(GoodNameShow,QuantityShow ,GoodUnitPriceShow) ;
Run Code Online (Sandbox Code Playgroud)