java如何从方法返回多个值

本文介绍三个方法,使java方法返回多个值。

  • 方法1:使用集合类
  • 方法2:使用封装对象
  • 方法3:使用引用传递

示例代码如下:

import java.util.HashMap;
import java.util.Map;

public class Test {

    /**
     * 方法1:使用集合类 (Map以外的集合类也可以随意使用)
     * 目标:返回一个数组的最大值和最小值
     */
    public Map<String, Integer> test1(int[] arr) {
        Map<String, Integer> map = new HashMap<String, Integer>();

        int max = Integer.MIN_VALUE;
        int min = Integer.MAX_VALUE;
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] > max) {
                max = arr[i];
            }
            if (arr[i] < min) {
                min = arr[i];
            }
        }

        map.put("max", max);
        map.put("min", min);

        return map;
    }

    /**
     * 方法2:使用封装对象
     * 目标:返回一个数组的最大值和最小值
     */
    public Result test2(int[] arr) {
        Result result = new Result();

        int max = Integer.MIN_VALUE;
        int min = Integer.MAX_VALUE;
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] > max) {
                max = arr[i];
            }
            if (arr[i] < min) {
                min = arr[i];
            }
        }

        result.setMax(max);
        result.setMin(min);

        return result;
    }

    /**
     * 方法3:使用引用传递 (不适用基本类型及其封装类和String类型)
     * 目标:返回数组长度,同时获取最大值和最小值
     */
    public int test3(int[] arr, Result result) {
        int max = Integer.MIN_VALUE;
        int min = Integer.MAX_VALUE;

        for (int i = 0; i < arr.length; i++) {
            if (arr[i] > max) {
                max = arr[i];
            }
            if (arr[i] < min) {
                min = arr[i];
            }
        }

        result.setMax(max);
        result.setMin(min);

        int total = arr.length;
        return total;
    }
    
    /**
     * 测试main
     */
    public static void main(String[] args) {
        Test t = new Test();

        int[] arr = { 1, 2, 3, 4, 5, 6 };
        
        // ----------方法1测试-----------
        // Map<String, Integer> map = t.test1(arr);
        // System.out.println("max : " + map.get("max"));
        // System.out.println("min : " + map.get("min"));

        // ----------方法2测试-----------
        // Result result = t.test2(arr);
        // System.out.println("max : " + result.getMax());
        // System.out.println("min : " + result.getMin());

        // ----------方法3测试-----------
        Result result = new Result();
        int total = t.test3(arr, result);
        System.out.println("total : " + total);
        System.out.println("max : " + result.getMax());
        System.out.println("min : " + result.getMin());

    }

}

class Result {
    int max;
    int min;

    // 构造函数
    public Result() {
        super();
    }

    // getters/setters(略)
}
原文地址:https://www.cnblogs.com/zj0208/p/6207077.html