java中return如何返回两个值

35次阅读
没有评论

共计 1419 个字符,预计需要花费 4 分钟才能阅读完成。

在 Java 中,return 语句只能返回一个值。但是我们可以通过以下几种方式来返回多个值:

  1. 使用数组:可以创建一个数组,并将多个值存储在数组中,然后将该数组作为返回值返回。
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. 使用自定义对象:可以创建一个包含多个值的自定义对象,然后将该对象作为返回值返回。
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;
    }
}

注意:以上方法中,返回的多个值是整体返回的,调用者可以通过相应的方式获取其中的值。

丸趣 TV 网 – 提供最优质的资源集合!

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2023-12-13发表,共计1419字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)