数组工具类 - ArrayUtil.java

数组工具类,提供数组、对象之间转换的方法。

 

源码如下:(点击下载 - ArrayUtil.java 、commons-lang-2.6.jar)

 1 import java.lang.reflect.Array;
 2 import java.util.Collection;
 3 import java.util.Iterator;
 4 
 5 import org.apache.commons.lang.StringUtils;
 6 
 7 /**
 8  * 数组工具类
 9  * 
10  */
11 public class ArrayUtil {
12 
13     private transient static final String DEFAULT_JOIN_STR = ",";
14 
15     /**
16      * 连接字符串 如:[1,2,3,4],将会返回"1,2,3,4"
17      *
18      * @param arr
19      *            an array of {@link java.lang.Object} objects.
20      * @return a {@link java.lang.String} object.
21      */
22     public static final String join(final Object[] arr) {
23         return join(arr, DEFAULT_JOIN_STR);
24     }
25 
26     /**
27      * 连接字符串 如: join([1,2,3,4],"x"]) 将会返回"1x2x3x4"
28      *
29      * @param arr
30      *            an array of {@link java.lang.Object} objects.
31      * @param joinStr
32      *            a {@link java.lang.String} object.
33      * @return a {@link java.lang.String} object.
34      */
35     public static final String join(final Object[] arr, final String joinStr) {
36         if (arr == null || arr.length < 1) {
37             return StringUtils.EMPTY;
38         }
39         final StringBuffer sb = new StringBuffer(String.valueOf(arr[0]));
40         for (int i = 1, len = arr.length; i < len; i++) {
41             sb.append(StringUtils.isNotEmpty(joinStr) ? joinStr : StringUtils.EMPTY).append(String.valueOf(arr[i]));
42         }
43         return sb.toString();
44     }
45 
46     /**
47      * 集合转数组
48      *
49      * @param collection
50      *            集合
51      * @param clazz
52      *            类型
53      * @return 数组
54      * @param <T>
55      *            a T object.
56      */
57     @SuppressWarnings("unchecked")
58     public static final <T> T[] toArray(final Collection<T> collection, final Class<T> clazz) {
59         if (collection == null) {
60             return null;
61         }
62         final T[] arr = (T[]) Array.newInstance(clazz, collection.size());
63         return collection.toArray(arr);
64     }
65 
66     /**
67      * 集合转对象数组
68      *
69      * @param collection
70      *            集合
71      * @return 对象数组
72      */
73     public static final Object[] toObjectArray(final Collection<?> collection) {
74         if (collection == null) {
75             return null;
76         }
77         final Object[] arr = (Object[]) Array.newInstance(Object.class, collection.size());
78         int i = 0;
79         for (Iterator<?> it = collection.iterator(); it.hasNext();) {
80             arr[i++] = it.next();
81         }
82         return arr;
83     }
84 
85 }

 

posted @ 2016-02-19 12:30  小周JAVA技术分享  阅读(2831)  评论(0编辑  收藏  举报