关于函数:在Java中返回多个值

Return multiple values in Java

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

我的代码:

1
2
3
4
5
6
7
8
9
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 ;
}


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

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

在您的情况下,您显然需要定义一个类Show,它可能具有字段namequantityprice

1
2
3
4
5
public class Show {
    private String name;
    private int price;
    // add other fields, constructor and accessors
}

然后将您的功能更改为

1
2
3
 public  Show  test(){
      ...
      return new Show(GoodNameShow,QuantityShow ,GoodUnitPriceShow) ;


我已经开发出一种非常基本的方法来处理这种情况。

我在字符串中使用了分隔符的逻辑。

例如,如果您需要返回相同的函数
1. int值
2.双重价值
3.字符串值

您可以使用分隔符字符串

例如,",。,"这种字符串通常不会出现在任何地方。

您可以返回由该分隔符分隔的所有值组成的String
" ,。,,。,<字符串值>"

并转换为使用String.split(separtor)[index]调用函数的等效类型

请参考以下代码进行解释-

分隔符用于=",。,"

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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);

 }
}

当您不想为仅函数返回而增加类数时,可以将此方法用作快捷方式

取决于情况对采取哪种方法的情况。