栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

本文实例讲述了java实现从方法返回多个值功能。分享给大家供大家参考,具体如下:

这里介绍三个方法,使java方法返回多个值。

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

示例代码如下:

import java.util.HashMap;
import java.util.Map;
public class Test {
  
  public Map test1(int[] arr) {
    Map map = new HashMap();
    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 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;
  }
  
  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;
  }
  
  public static void main(String[] args) {
    Test t = new Test();
    int[] arr = { 1, 2, 3, 4, 5, 6 };
    // ----------方法1测试-----------
    // Map 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程序设计有所帮助。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/143589.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号