21xrx.com
2025-03-23 17:25:10 Sunday
文章检索 我的文章 写文章
Java中如何使用return返回多个参数?
2023-06-12 03:20:49 深夜i     --     --
Java return 多个参数

在Java中,一个方法只能返回一个值。但有些情况需要返回多个参数,这时我们可以使用类、数组、集合等进行处理,下面简单介绍三种方法。

方法一:使用数组

我们可以定义一个数组,将需要返回的多个参数存入该数组,并将该数组作为返回值返回。

public static int[] getNums(){
  int[] nums = 3;
  return nums;
}

在调用该方法时,可以使用以下方式获取返回值:

int[] result = getNums();
int first = result[0];
int second = result[1];
int third = result[2];

方法二:使用集合

我们也可以使用集合来存储多个参数,这时我们需要导入java.util包。

public static List
  getNums(){
 
  List
  nums = new ArrayList<>();
 
  nums.add(1);
  nums.add(2);
  nums.add(3);
  return nums;
}

在调用该方法时,可以使用以下方式获取返回值:

List
  result = getNums();
 
int first = result.get(0);
int second = result.get(1);
int third = result.get(2);

方法三:使用自定义类

我们也可以定义一个类,将需要返回的多个参数作为该类的属性,然后将该类作为返回值返回。

public static class Num{
  int first;
  int second;
  int third;
  public Num(int first, int second, int third)
    this.first = first;
    this.second = second;
    this.third = third;
  
}
public static Num getNums(){
  return new Num(1,2,3);
}

在调用该方法时,可以使用以下方式获取返回值:

Num result = getNums();
int first = result.first;
int second = result.second;
int third = result.third;

  
  

评论区