Java_可變參數類型


Java方法中的可變參數類型,也稱為不定參數類型,是一個非常重要的概念

舉栗子

public class TestVarArgus {
	public static void dealArray(int... intArray) {
		for (int i : intArray)
			System.out.print(i + " ");
 
		System.out.println();
	}
 
	public static void main(String args[]) {
		dealArray();
		dealArray(1);
		dealArray(1, 2, 3);
	}
}

輸出:

1   
1 2 3  

類似數組?

和數組很像,其實就是。編譯器會在悄悄地把這最后一個形參轉化為一個數組形參,並在編譯出的class文件里作上一個記號,表明這是個實參個數可變的方法

dealArray();//dealArray(int[] intArray{}); 
dealArray(1);//dealArray(int[] intArray{1}); 
dealArray(1,2,3);//dealArray(int[] intArray{1, 2, 3}); 

和數組方法在一起無法重載。說明參數類型一致。

public static void dealArray(int... intArray) {
	
}
 
public static void dealArray(int[] intArray) {
	// 會有Duplicate method dealArray(int[]) in type TestVarArgus的錯誤
}

互相兼容嗎?

public static void dealArray(int... intArray) {
	for (int i : intArray)
		System.out.print(i + " ");
	System.out.println();
}

調用:
int[] intArray = { 1, 2, 3 };
dealArray(intArray);// 通過編譯,正常運行
public static void dealArray(int[] intArray) {
	for (int i : intArray)
		System.out.print(i + " ");
	System.out.println();
}
調用:
dealArray(1, 2, 3);// 編譯錯誤
可變參數是兼容數組類參數的,但是數組類參數卻無法兼容可變參數

只能放在最后一項

public static void dealArray(int count, int... intArray) {
 
}

public static void dealArray(int... intArray, int count) {
	// 編譯報錯,可變參數類型應該作為參數列表的最后一項

}

優先級

public class TestVarArgus {
	public static void dealArray(int... intArray) {
		System.out.println("1");
	}
 
	public static void dealArray(int count, int count2) {
		System.out.println("2");
	}
 
	public static void main(String args[]) {
		dealArray(1, 2);
	}
}

你覺得會執行哪一個方法???
會輸出2,能匹配定長的方法,那么優先匹配該方法。含有不定參數的那個重載方法是最后被選中的


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM