将对象数组转换为List,空类型安全。
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* 对象数组转换为List
*
* @author leizhimin 2010-4-29 19:08:12
*/
public class TestArray {
public static void main(String[] args) {
String[] a1 = { "a", "b", "c"};
String[] a2 = {};
List s1 = array2List(a1);
List s2 = array2List(a2);
List s3 = array2List2(a1);
List s4 = array2List2(a2);
List s5 = array2List( null);
List s6 = array2List2( null);
System.out.println(s1.size());
System.out.println(s2.size());
System.out.println(s3.size());
System.out.println(s4.size());
System.out.println(s5.size());
System.out.println(s6.size());
}
/**
* 数组转换为List(不推荐使用)
*
* @param arr 数组
* @return List
*/
public static List array2List(Object[] arr) {
List list = new ArrayList();
if (arr == null) return list;
for ( int i = 0; i < arr.length; i++) {
list.add(arr[i]);
}
return list;
}
/**
* 数组转换为List(推荐使用)
*
* @param arr 数组
* @return List
*/
public static List array2List2(Object[] arr) {
List list = new ArrayList();
if (arr == null) return list;
list = Arrays.asList(arr);
return list;
}
}
import java.util.Arrays;
import java.util.List;
/**
* 对象数组转换为List
*
* @author leizhimin 2010-4-29 19:08:12
*/
public class TestArray {
public static void main(String[] args) {
String[] a1 = { "a", "b", "c"};
String[] a2 = {};
List s1 = array2List(a1);
List s2 = array2List(a2);
List s3 = array2List2(a1);
List s4 = array2List2(a2);
List s5 = array2List( null);
List s6 = array2List2( null);
System.out.println(s1.size());
System.out.println(s2.size());
System.out.println(s3.size());
System.out.println(s4.size());
System.out.println(s5.size());
System.out.println(s6.size());
}
/**
* 数组转换为List(不推荐使用)
*
* @param arr 数组
* @return List
*/
public static List array2List(Object[] arr) {
List list = new ArrayList();
if (arr == null) return list;
for ( int i = 0; i < arr.length; i++) {
list.add(arr[i]);
}
return list;
}
/**
* 数组转换为List(推荐使用)
*
* @param arr 数组
* @return List
*/
public static List array2List2(Object[] arr) {
List list = new ArrayList();
if (arr == null) return list;
list = Arrays.asList(arr);
return list;
}
}
3
0
3
0
0
0
Process finished with exit code 0
0
3
0
0
0
Process finished with exit code 0
本文转自 leizhimin 51CTO博客,原文链接:http://blog.51cto.com/lavasoft/307469,如需转载请自行联系原作者