Java入门系列(六)返回多个值、

使用集合类

/**
     * 方法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;
    }

使用封装对象

public class Result {
       private int max;
       private int min;
        // 构造函数
        public Result() {
            super();
        }
        public int getMax() {
            return max;
        }
        public void setMax(int max) {
            this.max = max;
        }
        public int getMin() {
            return min;
        }
        public void setMin(int min) {
            this.min = min;
        }
    }
/**
     * 方法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());
    }
}

java ref out

猜你喜欢

转载自www.cnblogs.com/cnki/p/9290342.html