首页 > 代码库 > 【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
- 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 :
[html] view plaincopy
- [ABC, FGF, CID]
- [ABC, FGF, CID]
- [ABC, FGF, CID]
- [ABC, FGF, CID]
- [ABC, FGF, CID]
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。