首页 > 代码库 > 【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. 

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class ListUtil
{

    /**
     *Init the List with different methods. 
     * 
     * @time Jul 21, 2014 5:39:10 PM
     * @return void
     */
    public static void init()
    {
        // use new to init List
        List<String> firstList = new ArrayList<String>(0);
        firstList.add("ABC");
        firstList.add("FGF");
        firstList.add("CID");
        System.out.println(firstList);
        
        // use the string to init List
        List<String> testList = Arrays.asList("ABC", "FGF", "CID");
        System.out.println(testList);
        //output:[ABC, ABC, GFG, CID]
        
        /**
         * Notes: The following methods is dependent on the above List.
         */
        
        //use arrays and copy to init List
        List<String> copyList = Arrays.asList(new String[testList.size()]);
        Collections.copy(copyList,testList);
        System.out.println(copyList);
        
        //use new object and copy to init List
        copyList = new ArrayList<String>();
        Collections.addAll(copyList, new String[testList.size()]);
        Collections.copy(copyList,testList);
        System.out.println(copyList);
        
        //use the list.subList to init List
        List<String> strSubList = testList.subList(0, testList.size());
        System.out.println(strSubList);
    };
    
    public static void main(String[] args)
    {
        ListUtil.init();
    }
}

The result is :

[ABC, FGF, CID]
[ABC, FGF, CID]
[ABC, FGF, CID]
[ABC, FGF, CID]
[ABC, FGF, CID]



【DataStructure】 Five methods to init the List in java