随笔 - 45, 文章 - 2, 评论 - 11, 引用 - 0
数据加载中……

commons-lang源码学习之ArrayUtils

1、比较两个对象是否类型相同

array1.getClass().getName().equals(array2.getClass().getName()

2、倒置(reverse)数组中的元素

         int i = 0;
        int j = array.length - 1;
        Object tmp;
        while (j > i) {
            tmp = array[j];
            array[j] = array[i];
            array[i] = tmp;
            j--;
            i++;
          }

3、得到数组的容器类型

array.getClass().getComponentType();

4、lastIndex()这类方法的实现

for (int i = startIndex; i >= 0; i--) {
              if (objectToFind.equals(array[i])) {
                  return i;
              }
}

5、isEmpty()这类方法的实现只要一句话,isNotEmpty方法依此推

return array == null || array.length == 0;

6、将两个数组合并addAll

       boolean[] joinedArray = new boolean[array1.length + array2.length];
       System.arraycopy(array1, 0, joinedArray, 0, array1.length);
       System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);

7、将新元素加入到数组中

            int arrayLength = Array.getLength(array);
            Object newArray = Array.newInstance(array.getClass().getComponentType(), arrayLength + 1);
            System.arraycopy(array, 0, newArray, 0, arrayLength);
            return newArray;

8、获得数组长度的方法

int arrayLength = Array.getLength(array);

9、以反射的方式获得数组对象

Array.newInstance(array.getClass().getComponentType(), arrayLength + 1)

10、将某一元素从数组中移除

Object result = Array.newInstance(array.getClass().getComponentType(), getLength(array)- 1);
       System.arraycopy(array, 0, result, 0, index);
       if (index < length - 1) {
           System.arraycopy(array, index + 1, result, index, length - index - 1);
       }

posted on 2011-03-08 15:01 jack zhai 阅读(788) 评论(0)  编辑  收藏 所属分类: java2 se


只有注册用户登录后才能发表评论。


网站导航: