在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;
}
}
注意:以上方法中,返回的多個值是整體返回的,調用者可以通過相應的方式獲取其中的值。