码迷,mamicode.com
首页 > 编程语言 > 详细

【DataStructure】 Five methods to init the List in java

时间:2014-07-22 14:37:43      阅读:211      评论:0      收藏:0      [点我收藏+]

标签:collection   list   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

标签:collection   list   java   

原文地址:http://blog.csdn.net/sxb0841901116/article/details/38032295

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!