可变参数,数组与聚合之间的转换
可变参数,数组与集合之间的转换
import java.util.*; /* 数组转成集合。Arrays.asList([]); 注意:变成集合后,长度是固定,不可以使用集合的增删方法。 思想: 通过集合的方式来操作数组。 集合变数组:Collection中的<T> toArray(T[]) 高级for循环,必须要有被遍历的目标(Collection 或者 数组)。 */ class ArraysDemo2 { public static void main(String[] args) { // listToArray(); int[] arr = {4,2,1,7}; for(int i : arr) { System.out.println(i); } ArrayList<String> al = new ArrayList<String>(); al.add("sdfsdf0"); al.add("sdfsdf1"); al.add("sdfsdf2"); al.add("sdfsdf3"); for(String s : al) { System.out.println(s); } for(int x=0;x<al.size(); x++) { System.out.println(al.get(x)); } } /* 集合变数组。 */ public static void listToArray() { ArrayList<String> al = new ArrayList<String>(); al.add("sdfsdf0"); al.add("sdfsdf1"); al.add("sdfsdf2"); al.add("sdfsdf3"); String[] arr = al.toArray(new String[al.size()]); for(int x=0;x<arr.length; x++) { System.out.println(arr[x]); } } /* 数组变集合 */ public static void arrayToList() { // List<String> list = Arrays.asList("abc","kk","heh"); // String[] arr = {"hehe","heihei"}; int[] arr = {4,2,1,7}; List<int[]> list = Arrays.asList(arr); // list.add("zzz"); System.out.println(list.size()); for(int x=0; x<list.size(); x++) { System.out.println(list.get(x)); } Object obj = new int[2]; int[] arr1 = (int[])obj; for(int x=0; x<arr1.length; x++) { System.out.println(arr1[x]); } } public static void show(int a,String... arr) { for(int x=0; x<arr.length; x++) System.out.println(arr[x]); } public static void getSum(int... a) { int sum = 0; for(int x=0; x<a.length; x++) { sum += a[x]; } System.out.println(sum); } /* public static void show(String[] str) { } */ }
1 楼
greemqqran
2012-05-08
Arrays.asList
2 楼
greemqqran
2012-05-08
这方法 源码,是怎么的哦?