JAVA基礎--可變參,自動裝箱與拆箱,類型轉換

* 可變參數的內部原理是數組

public class Test{
	public static void main(String[] args) {
		Test6 t =new Test6();
		//1.傳入1到多個int類型的數據。
		t.method4(1);
		t.method4(1,2,3,4,5,6,67,7,8,8,9,9);
		int a[]=new int [2];
		//2.傳入數組
		t.method4(a);
		//3、空參   表示傳入的是,長度爲0的數組。
		t.method4();
		//4、引用數據的類型的默認值是null,所以還可以傳入null
//		t.method4(null);
		t.method5("", 1,2,34,4,6,7,8);
	}
	
	//可變參數: 實際上指的是參數的個數可變。
	public void method4(int...a){
		//遍歷數組。		
		for(int i:a){
			System.out.print(i+" ");
		}
		System.out.println("長度是:"+a.length);
	}
	//可變參數一定要放在參數列表的末尾位置。而且可變參數只能有一個。
	public void method5(String str,int...b){
		System.out.println(str);
		for(int j:b){
			System.out.println(j);
		}
	}
}


自動裝箱:int類型轉換成Integer
 裝箱的意義:
  1、提供了一些屬性和方法,方便我們操作數據。
 2、有些地方,只能使用對象 [集合中的元素,只能是引用類型]

  3 封裝性  [一切皆對象]

當我們創建一個Integer對象時,可以這樣:

 Integer i = 100; (注意:不是 int i = 100; )

實際上,執行上面那句代碼的時候,系統爲我們執行了:Integer i = Integer.valueOf(100); 

此即基本數據類型的自動裝箱功能。
  • 什麼時候自動裝箱

例如:Integer i = 100;

相當於編譯器自動爲您作以下的語法編譯:Integer i = Integer.valueOf(100);

  • 什麼時候自動拆箱


自動拆箱(unboxing),也就是將對象中的基本數據從對象中自動取出。如下可實現自動拆箱:

Integer i 10//裝箱 
int t = i; //拆箱,實際上執行了 int t = i.intValue(); 

  在進行運算時,也可以進行拆箱。 

Integer i 10
System.out.println(i++); 


Integer的自動裝箱

//在-128~127 之外的數
 Integer i1 =200;  
 Integer i2 =200;          
 System.out.println("i1==i2: "+(i1==i2));                   
 // 在-128~127 之內的數
 Integer i3 =100;  
 Integer i4 =100;  
 System.out.println("i3==i4: "+(i3==i4));
 輸出的結果是:
    i1==i2: false
    i3==i4: true

說明:

equals() 比較的是兩個對象的值(內容)是否相同。

"==" 比較的是兩個對象的引用(內存地址)是否相同,也用來比較兩個基本數據類型的變量值是否相等。

查看Integer的源碼可以知道,它在-128到+127是引用的同一個地址,所以爲true,當不在這個範圍中,就會是false.

當然,當不使用自動裝箱功能的時候,情況與普通類對象一樣,請看下例:
 Integer i3 =new Integer(100); 
 Integer i4 =new Integer(100); 
 System.out.println("i3==i4: "+(i3==i4));//顯示false
  • String 的拆箱裝箱

先看個例子:

String str1 ="abc";
           String str2 ="abc";
           System.out.println(str2==str1);  //輸出爲 true 
System.out.println(str2.equals(str1));  //輸出爲 true 
            
           String str3 =new String("abc");
           String str4 =new String("abc"); 
           System.out.println(str3==str4);  //輸出爲 false 
System.out.println(str3.equals(str4));  //輸出爲 true
String的裝箱是放入常量池中,引用的是同一個地址;當使用new時,new出的是不同的對象,會各自新開闢一個空間,地址就會不相同。

自動類型轉換的三個條件:
  1、類型要兼容、
  2、我們要轉換的範圍一定要大於我們原來的範圍。【小轉大】
  3、可能丟失精度、【整型轉換浮點型的時候。】

強制類型轉換:
  1、類型要兼容、
  2、我們要轉換的類型範圍小於我們本身的類型範圍。【大轉小】
  3、有可能會數據溢出。

public class Test {
	public static void main(String[] args) {
		//我們知道long型的數值,要加L或l,爲什麼下面的代碼並沒有加,但是沒有錯誤?
		//int型的21414轉換成了long型。
		long a=21414;
		//b的數值範圍已經超過了int的範圍,所以只能在後面加L或者l。
		long b=4372910475342L;
		//long型的數值,要轉換成double類型。
		double c=4793L;
		System.out.println(c);
                //將long類型的數值,強制轉換成byte類型。
		 byte a=(byte) 62L;
		 System.out.println(a);
	}
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章