您的位置:首页 > 编程语言 > Java开发

java 11:数组作为函数参数,数组做为函数返回值

2014-06-28 00:06 741 查看
1 数组作为参数

我们可以将数组作为参数,传入到函数中,其实就像我们main函数中 public void main(String [] args){};就是用数组作为函数参数;

又如,

public class ArrayPar
{
<span style="white-space:pre">	</span>public static void printArray(int [] array)
<span style="white-space:pre">	</span>{
<span style="white-space:pre">		</span>for(int i=0;i<array.length;i++)
<span style="white-space:pre">			</span>System.out.print(array[i]+"  ");
<span style="white-space:pre">	</span>}
}
我们可以这样调用 ArrayPar.printt(new int[ ]{3,2, 5,67});调用数组

这里的new int[ ]{3,2,5,67};他也是一种创建数组的方法,只是这种方法创建出来的数组是没有名字的,所以叫匿名数组。很多时候在只使用一次的时候可以使用匿名数组的方法法,类似的还有匿名类。

Java uses pass-by-value to pass arguments to a method. There are important differences

between passing the values of variables of primitive data types and passing arrays.

■ For an argument of a primitive type, the argument’s value is passed.

■ For an argument of an array type, the value of the argument is a reference to an array;

this reference value is passed to the method. Semantically, it can be best described as

pass-by-sharing, i.e., the array in the method is the same as the array being passed.

So if you change the array in the method, you will see the change outside the

method.

java 使用值传参(pass_by_value)的方式来传递函数参数,只是值传递方式在处理原始数据类型参数与引用类型参数时候有不同,如果一个参数是原始数据类型,那么参数变量的值传递进去。如果是引用类型,是传进了引用变量的值(也就是说,只是将指向数据的引用的值给传进去了,也就是被调用的函数新建的空间放的是这个引用的值,那么也就是也指向了数组存在的内存),所以同样是值传递,引用类型的传入的当然是引用变量的值,指向了同一数组,那么函数内对数组进行的修改在函数退出后依旧是有效的。

例子:

public class ArrayPar
{
	public static void main(String [] args)
	{
		int x=1;
		int y[]={1,2,3};
		change(x,y);
		System.out.println("x="+x+",y[0]="+y[0]);
	}
	public static void change(int num,int [] array)
	{
		num=100;
		array[0]=100;
	}
}


图形表示:



这里同时注意一下,当我们用new 以及malloc这些的内存空间是在堆上heap,而像我们被调用的函数中使用的这些变量等在栈上。在调用changes时候,x的值被传入,在被调用的函数中重新开辟一个空间来放这个基本数据类型参数,但是int [ ] y ,将y传入其实就是传入了引用,在被调用的函数的栈上只会开辟一个空间来存放这个引用,所以被调用的函数与调用者 中两个引用指向堆上同一块内存。

2 数组做为函数返回值

public static<span style="color:#ff0000;"> int []</span> reverse(int [] array)
	{
		int [] result=new int[array.length]
		for(int i=0;i<array.length;i++)
		{
			result[i]=array[lenght-i];
		}
		<span style="color:#ff6666;">return result;</span>
	}
在将数组作为函数返回值时候如上红色标出的,就是在函数名字前加上返回值类型是int [ ] 表示返回一个int型数组,在函数体内最后返回是result这样的函数引用。

Case Study: Counting the Occurrences of Each Letter

write a program to count the occurrences of each letter in an random array of lower characters.

那么我们可以怎么做呢?

1)首先是要产生一个随机char数组 creatArray();(是否记得前边说过产生[a,a+b)之间的一个随机数 为 a+Math.random()*b,是否记得我们创建过获取任意字符的一个类?)

2) 创建一个数组 int [ ] count,长度26,准备来存放各个字母的计数

3)对数组进行循环 , 每读取一个字母ch,则 count[ch-'a']++;

class RandomChar
{
	public static char getRandomChar(char ch1,char ch2)
	{
		return (char)(ch1+Math.random()*(ch2-ch1+1));
	}
	public static char getLowerCaseLetter()
	{
		return getRandomChar('a','z');
	}
	public static char getUpperCaseLetter()
	{
		return getRandomChar('A','Z');
	}
	public static char getDigitalLetter()
	{
		return getRandomChar('0','9');
	}
	public static char getRandomLetter()
	{
		return getRandomChar('\u0000','\uFFFF');
	}
}
public class CountOccur
{
	public static void main(String [] args)
	{
		 char [] array=CreateArray();
		 int [] count = new int[26];
		 for(int i=0;i<array.length;i++)
		 {
			 count[array[i]-'a']++;
		 }
		 for(int i=0;i<count.length;i++)
		 {
			System.out.print((char)(i+'a')+": "+count[i]+"    ");
			if((i+1)%10==0) System.out.println();
		 }
		 
		 
	}
	//产生一个100个元素的小写随机数组
	public static char[] CreateArray()
	{
		char [] a=new char[100];
		for(int i=0;i<a.length;i++)
		{
			a[i]=RandomChar.getLowerCaseLetter();
		}
		return a;
	}
}




3 可变长度参数列表

You can pass a variable number of arguments of the same type to a method. The parameter in

the method is declared as follows:

typeName... parameterName

In the method declaration, you specify the type followed by an ellipsis Only one vari-

able-length parameter may be specified in a method, and this parameter must be the last para-

meter. Any regular parameters must precede it.

Java treats a variable-length parameter as an array. You can pass an array or a variable

number of arguments to a variable-length parameter. When invoking a method with a variable

number of arguments, Java creates an array and passes the arguments to it

我们可以传递类型相同,但个数可以变化的参数到函数中,如果有这个需求的话,这时候我们只需要在形式参数中使用 typename...parameterName就可以达到这个目的,要注意,在这里声明的该变长参数必须是最后一个参数,任何常规参数必须在他之前,也就是说你可以有 MethodName(char b, double c, int ... nums) 这样的形式即int ...
nums必须在最后一个位置,你不能将int ... nums 声明在参数参数列表的非最后位置。

java将可变长参数当做数组对待。可以将一个数组或者可的参数个数传递给该参数(注意,我们这里说该参数就是 typeName ... parameterName这整个结构),无论哪种形式,java会创建一个数组并把参数传给他,注意这里体会原文说的When invoking a method with a variable

number of arguments, java Create an array and passes the arguments to it,也就是说,如果你是传入几个变长的变量,那么在调用时候java先将创建一个数组来装这几个实际参数,然后再执行调用的函数,如果本身我们传入一个数组,其实他并不会创建一个新的数组来装,还是一样像上面指向了已经分配的数组空间,所以在被调用的函数中对数组的改变在退出时候还是有效的(这是我用例子试了下体会到的)

public class VariablePar
{
	public static void main(String [] args)
	{
		int array[]={1,4,7,2,0};
		System.out.println("max="+findMax(array));
		ifChange(array);
		System.out.println("array[0]="+array[0]);
		ifChange(1,45,33);
	}
	public static int findMax(int ... nums)
	{
		if(nums.length==0) 
		{
			System.out.println("No argumment passed");
			return -1;
		}
		int max=nums[0];
		for(int i=1;i<nums.length;i++)
		{
			if(max<nums[i]) max=nums[i];
		}
		return max;
	}
	//测试这里究竟是新创建一个数组还是相当于把引用传进来而已
	public static void ifChange(int ... nums)
	{
		nums[0]=100;
	}
}
这里,我们从findMax中看到,他不用先说明 什么就可以直接使用nums.lenght 说明确实java是完全将这类型的参数当做一个数组来处理了,二在ifChange中,我们看到输出的是array[0]=100,说明我们在调用ifChange(array)时候并不是重新创建一个新的数组,而是还是一样像前边的传入了引用,被调用者还是指向了相同的数组空间。但是在ifChage(1,45,33)这个调用时候,java就会先new int[ ]{1,45,33} 这样,然后形参nums再指向它,其实这样返回后应该就不会改变了1的值吧?

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: