Java 中的文法糖

來源:互聯網
上載者:User

標籤:size   number   變長參數   增強   反編譯   迴圈   word   內容   檢查   

定義:指的是,在電腦語言中添加某種文法,這種文法能使程式員更方便的使用語言開發程式,同時增強程式碼的可讀性,避免出錯的機會;但是這種文法對語言的功能並沒有影響。
Java中的泛型,變長參數,自動拆箱/裝箱,條件編譯等都是

 

泛型:ava的泛型只在原始碼存在,只供編輯器檢查使用,編譯後的位元組碼檔案已擦除了泛型型別

public static void main(String[] args) {      List<String> stringList = new ArrayList<String>();      stringList.add("oliver");      System.out.println(stringList.get(0));  }  

        將上面的代碼的位元組碼反編譯後:

 public static void main(String args[])  {      List stringList = new ArrayList();      stringList.add("oliver");      System.out.println((String)stringList.get(0));  }  

 

自動拆箱/裝箱

     裝箱過程:把基本類型用它們對應的封裝類型進行封裝,使 基本類型具有對象特徵
     拆箱過程:與裝箱過程相反,把封裝類型轉換成基本類型。  
  • 基礎資料型別 (Elementary Data Type)與對象的差別 

基礎資料型別 (Elementary Data Type)不是對象,也就是使用int、double、boolean等定義的變數、常量。

基礎資料型別 (Elementary Data Type)沒有可調用的方法。

eg:  int t = 1;     t.  後面是沒有方法滴。

 Integer t =1; t.  後面就有很多方法可讓你調用了。

 
  • 什麼時候自動裝箱

例如:Integer i = 100;

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

 
  • 什麼時候自動拆箱

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

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

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

1 Integer i = 10; 
2 System.out.println(i++);備忘:包裹類型的“==”運算在沒有遇到算數運算子的情況下不會自動拆箱 
  • Integer的自動裝箱

 

 說明:

equals() 比較的是兩個對象的值(內容)是否相同。(這裡的方法已經是重寫過的)

"==" 比較的是兩個對象的引用(記憶體位址)是否相同,也用來比較兩個基礎資料型別 (Elementary Data Type)的變數值是否相等。比較的是是不是同一個對象

 

前面說過,int 的自動裝箱,是系統執行了 Integer.valueOf(int i),先看看Integer.java的源碼:

123456 public static Integer valueOf(int i) {    if(i >= -128 && i <= IntegerCache.high)  // 沒有設定的話,IngegerCache.high 預設是127        return IntegerCache.cache[i + 128];    else        return new Integer(i);}

  

對於–128到127(預設是127)之間的值,Integer.valueOf(int i) 返回的是緩衝的Integer對象(並不是建立對象)

所以範例中,i3 與 i4實際上是指向同一個對象。

而其他值,執行Integer.valueOf(int i) 返回的是一個建立的 Integer對象,所以範例中,i1與i2 指向的是不同的對象。

 

 //不使用自動拆裝箱和其他的對象的用法是一樣的

1 Integer i3 =new Integer(100); 
2 Integer i4 =new Integer(100); 
3 System.out.println("i3==i4: "+(i3==i4));//顯示false  迴圈曆遍(foreach)  


public static void main(String[] args) {
List<Integer> list = new ArrayList<Integer>();
for(Integer num : list){
System.out.println(num);
}
}

 

Java 中的文法糖

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.