【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]



郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。