在Java中,return语句只能返回一个值。但是我们可以通过以下几种方式来返回多个值:
public class Main {
public static void main(String[] args) {
int[] result = returnMultipleValues();
int value1 = result[0];
int value2 = result[1];
System.out.println(value1 + " " + value2);
}
public static int[] returnMultipleValues() {
int value1 = 10;
int value2 = 20;
int[] result = {value1, value2};
return result;
}
}
public class Main {
public static void main(String[] args) {
CustomObject result = returnMultipleValues();
int value1 = result.getValue1();
int value2 = result.getValue2();
System.out.println(value1 + " " + value2);
}
public static CustomObject returnMultipleValues() {
int value1 = 10;
int value2 = 20;
CustomObject result = new CustomObject(value1, value2);
return result;
}
}
class CustomObject {
private int value1;
private int value2;
public CustomObject(int value1, int value2) {
this.value1 = value1;
this.value2 = value2;
}
public int getValue1() {
return value1;
}
public int getValue2() {
return value2;
}
}
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Integer> result = returnMultipleValues();
int value1 = result.get(0);
int value2 = result.get(1);
System.out.println(value1 + " " + value2);
}
public static List<Integer> returnMultipleValues() {
int value1 = 10;
int value2 = 20;
List<Integer> result = new ArrayList<>();
result.add(value1);
result.add(value2);
return result;
}
}
注意:以上方法中,返回的多个值是整体返回的,调用者可以通过相应的方式获取其中的值。