Application case of array in java

/*
   
A method can have 0, 1, multiple parameters; but it can only have 0 or 1 return value, and cannot have multiple return values.
    What if you want to return multiple result data in a method?
    Solution: Use an array as the return value type.

    Any data type can be used as a method's parameter type or return value type.

    The array is used as the method parameter, and what is passed in is actually the address value of the array.
    As the return value of the method, the array is actually the address value of the array.
 */

public class User {
	
	public static void main(String[] args) {
		User user = new User();
		double[] res = user.calculate(10, 20, 30);
		System.out.println("函数返回值内存地址" + System.identityHashCode(res) + ",返回值为[" + res[0] + ", " + res[1] + "]");
		System.out.println("------------------------------------------------------");
	}
	
	public double[] calculate(double number1, double number2, double number3) {
		/*
		 * 一个方法可以有0、1、多个参数;但是只能有0或者1个返回值,不能有多个返回值。 如果希望一个方法当中产生了多个结果数据进行返回,怎么办?
		 * 解决方案:使用一个数组作为返回值类型即可。
		 * 
		 * 任何数据类型都能作为方法的参数类型,或者返回值类型。
		 * 
		 * 数组作为方法的参数,传递进去的其实是数组的地址值。 数组作为方法的返回值,返回的其实也是数组的地址值。
		 */
		double sum = number1 + number2 + number3; // 总和
		double avg = sum / 3; // 平均数
		// 两个结果都希望进行返回
		// 需要一个数组,也就是一个塑料袋,数组可以保存多个结果
		/*
		 * double[] array = new double[2]; 
		 * array[0] = sum; //总和
		 *  array[1] = avg; //平均数
		 */

		double[] array = { sum, avg };
		System.out.println("-------------这是函数内部-------------");
		System.out.println("calculate方法内部数组是:[" + array[0] + ", " + array[1] + "]");
		System.out.println("函数返回值内存地址" + System.identityHashCode(array));
		System.out.println("-------------这是函数内部-------------");
		return array;
	}
}

The results of the operation are as follows:

Guess you like

Origin blog.csdn.net/czh500/article/details/114852072