溫馨提示×

java中return如何返回兩個值

小億
164
2023-11-10 10:29:57
欄目: 編程語言

在Java中,return語句只能返回一個值。但是我們可以通過以下幾種方式來返回多個值:

  1. 使用數(shù)組:可以創(chuàng)建一個數(shù)組,并將多個值存儲在數(shù)組中,然后將該數(shù)組作為返回值返回。
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;
    }
}
  1. 使用自定義對象:可以創(chuàng)建一個包含多個值的自定義對象,然后將該對象作為返回值返回。
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;
    }
}
  1. 使用容器類:可以使用容器類如List或Map來存儲多個值,然后將該容器類作為返回值返回。
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;
    }
}

注意:以上方法中,返回的多個值是整體返回的,調(diào)用者可以通過相應(yīng)的方式獲取其中的值。

0