加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java实现从方法返回多个值功能示例

发布时间:2020-12-14 21:19:59 所属栏目:Java 来源:网络整理
导读:本篇章节讲解java实现从方法返回多个值功能。供大家参考研究具体如下: 这里介绍三个方法,使java方法返回多个值。 方法1:使用集合类 方法2:使用封装对象 方法3:使用引用传递 示例代码如下: import java.util.HashMap;import java.util.Map;pu

本篇章节讲解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(略)
}

更多关于java相关内容感兴趣的读者可查看本站专题:《Java数组操作技巧总结》、《Java字符与字符串操作技巧总结》、《Java数学运算技巧总结》、《Java数据结构与算法教程》及《Java操作DOM节点技巧总结》

希望本文所述对大家java程序设计有所帮助。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读