java 11:數組作爲函數參數,數組做爲函數返回值

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的值吧?




發佈了112 篇原創文章 · 獲贊 15 · 訪問量 22萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章