2013年10月1日星期二

How to use a Java collection of some elements to initialize another collection .

Such as:

 ArrayList<Data> a = new ArrayList<Data>();
 a.add(d1);
 a.add(d2);
 a.add(d3);
   
// 如何使用 a 的部分元素, 如 从a 的第1个元素开始 对al 进行初始化? 
 ArrayList<Data> al = new ArrayList<Data>(a);   



There is no direct function , or faster way . ?
online, ME ! ! !
------ Solution ---------------------------------------- ----
turn into an array and then operate
java.util.Arrays There are many static methods.
List<String> a = new ArrayList<String>();
a.add("1");
a.add("2");
a.add("3");
a.add("4");
a.add("5");
a.add("6");

// 把a中的3、4、5拷贝到aa中
String[] arr = new String[a.size()];
arr = a.toArray(arr);
arr = Arrays.copyOfRange(arr, 2, 5);
List<String> aa = Arrays.asList(arr);

System.out.println(Arrays.toString(aa.toArray()));

------ Solution ------------------------------------- -------
landlord will not use list.subList (int startIndex, int endIndex) for part of the collection is a collection of his return spread your collection with this constructor is not on the line.

 ArrayList<Data> a = new ArrayList<Data>();
         a.add(d1);
         a.add(d2);
         a.add(d3);
 ArrayList<Data> al = new ArrayList<Data>(a.subList(1,a.size()));   

------ For reference only ----------------------------------- ----

is to use this , only to find ,

没有评论:

发表评论