首页 > 代码库 > 【DataStructure】 Five methods to init the List in java

【DataStructure】 Five methods to init the List in java

Do you know how to init list in other way except for new object? The following will give you serveral tips. If having other great idea, you are welcome to share. 

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. import java.util.ArrayList;  
  2. import java.util.Arrays;  
  3. import java.util.Collections;  
  4. import java.util.List;  
  5.   
  6. public class ListUtil  
  7. {  
  8.   
  9.     /** 
  10.      *Init the List with different methods.  
  11.      *  
  12.      * @time Jul 21, 2014 5:39:10 PM 
  13.      * @return void 
  14.      */  
  15.     public static void init()  
  16.     {  
  17.         // use new to init List  
  18.         List<String> firstList = new ArrayList<String>(0);  
  19.         firstList.add("ABC");  
  20.         firstList.add("FGF");  
  21.         firstList.add("CID");  
  22.         System.out.println(firstList);  
  23.           
  24.         // use the string to init List  
  25.         List<String> testList = Arrays.asList("ABC""FGF""CID");  
  26.         System.out.println(testList);  
  27.         //output:[ABC, ABC, GFG, CID]  
  28.           
  29.         /** 
  30.          * Notes: The following methods is dependent on the above List. 
  31.          */  
  32.           
  33.         //use arrays and copy to init List  
  34.         List<String> copyList = Arrays.asList(new String[testList.size()]);  
  35.         Collections.copy(copyList,testList);  
  36.         System.out.println(copyList);  
  37.           
  38.         //use new object and copy to init List  
  39.         copyList = new ArrayList<String>();  
  40.         Collections.addAll(copyList, new String[testList.size()]);  
  41.         Collections.copy(copyList,testList);  
  42.         System.out.println(copyList);  
  43.           
  44.         //use the list.subList to init List  
  45.         List<String> strSubList = testList.subList(0, testList.size());  
  46.         System.out.println(strSubList);  
  47.     };  
  48.       
  49.     public static void main(String[] args)  
  50.     {  
  51.         ListUtil.init();  
  52.     }  
  53. }  

The result is :

[html] view plaincopy在CODE上查看代码片派生到我的代码片
  1. [ABC, FGF, CID]  
  2. [ABC, FGF, CID]  
  3. [ABC, FGF, CID]  
  4. [ABC, FGF, CID]  
  5. [ABC, FGF, CID]