欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Arrays.asList方法總結(jié)

 更新時間:2017年02月02日 12:46:00   作者:胖大海Plus  
本文主要對Arrays.asList方法進行總結(jié)。具有很好的參考價值,下面跟著小編一起來看下吧

話不多說,請看代碼:

import java.util.Arrays; 
import java.util.List; 
/** 
 * 
 * 本類演示了Arrays類中的asList方法 
 * 通過四個段落來演示,體現(xiàn)出了該方法的相關(guān)特性. 
 * 
 * (1) 該方法對于基本數(shù)據(jù)類型的數(shù)組支持并不好,當(dāng)數(shù)組是基本數(shù)據(jù)類型時不建議使用 
 * (2) 當(dāng)使用asList()方法時,數(shù)組就和列表鏈接在一起了. 
 *   當(dāng)更新其中之一時,另一個將自動獲得更新。 
 *   注意:僅僅針對對象數(shù)組類型,基本數(shù)據(jù)類型數(shù)組不具備該特性 
 * (3) asList得到的數(shù)組是的沒有add和remove方法的 
 * 
 * 閱讀相關(guān):通過查看Arrays類的源碼可以知道,asList返回的List是Array中的實現(xiàn)的 
 * 內(nèi)部類,而該類并沒有定義add和remove方法.另外,為什么修改其中一個,另一個也自動 
 * 獲得更新了,因為asList獲得List實際引用的就是數(shù)組 
 */ 
public class AsListTest {  
  public static void main(String[] args) { 
    /* 段落一:基本數(shù)據(jù)類型使用asList中的問題 */ 
    /* 說明:雖然在JDK1.6中能夠?qū)⒒緮?shù)據(jù)類型的數(shù)組轉(zhuǎn)換成List,但還是有個缺陷 */ 
    int[] a_int = { 1, 2, 3, 4 }; 
    /* 預(yù)期輸出應(yīng)該是1,2,3,4,但實際上輸出的僅僅是一個引用, 這里它把a_int當(dāng)成了一個元素 */ 
    List a_int_List = Arrays.asList(a_int); 
    foreach(a_int_List); 
    /* 為此我們需要這樣遍歷其中元素 */ 
    foreachForBase(a_int_List);  
    /* 段落二:對象類型的數(shù)組使用asList,是我們預(yù)期的 */ 
    Integer[] a_Integer = new Integer[] { 1, 2, 3, 4 }; 
    List a_Integer_List = Arrays.asList(a_Integer); 
    foreach(a_Integer_List);  
    /* 段落三:當(dāng)更新數(shù)組或者asList之后的List,另一個將自動獲得更新 */ 
    a_Integer_List.set(0, 0); 
    foreach(a_Integer_List); 
    foreach(a_Integer); 
    a_Integer[0] = 5; 
    foreach(a_Integer_List); 
    foreach(a_Integer); 
    /* 段落四:對基本類型數(shù)組,通過asList之后的List修改對應(yīng)的值后,在運行時會報出異常 
     * 但是基本類型數(shù)組對應(yīng)的List是會發(fā)生變化的,這是毫無疑問的 
     */    
    /* 
     * a_int_List.set(0, 0); 
     * foreach(a_int_List); foreach(a_int); 
     */ 
    a_int[0] = 5; 
    foreachForBase(a_int_List); 
    foreach(a_int); 
  } 
  /* 打印方法 */ 
  private static void foreach(List list) { 
    for (Object object : list) { 
      System.out.print(object + " "); 
    } 
    System.out.println(); 
  } 
  private static void foreachForBase(List a_int_List) { 
    int[] _a_int = (int[]) a_int_List.get(0); 
    foreach(_a_int); 
  } 
  private static void foreach(int[] a_int) { 
    for (int i : a_int) { 
      System.out.print(i + " "); 
    } 
    System.out.println(); 
  } 
  private static void foreach(Integer[] _a_Integer) { 
    for (int i : _a_Integer) { 
      System.out.print(i + " "); 
    } 
    System.out.println(); 
  } 
} 

以上就是本文的全部內(nèi)容,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作能帶來一定的幫助,同時也希望多多支持腳本之家!

相關(guān)文章

最新評論