Home >Java >javaTutorial >How to return two values in java
How does a Java program return multiple values? There are many methods, let's take a look.
If you want to return multiple values, you can first create a class. This class has two member variables, making this class the returned object.
public class Result { int max; int min; // 构造函数 public Result() { super(); } // getters/setters(略) }
Here is a method to make Java return (return) two values:
Method 1: Use collection class Method 2: Use encapsulated object Method 3: Use reference passing .
Please see the example:
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()); } }
Related learning recommendations: java basic tutorial
The above is the detailed content of How to return two values in java. For more information, please follow other related articles on the PHP Chinese website!