neau火车

 

关于java 数组的一些知识

ArrayUtil
  让数组的长度容量涨一个
   

private static Object copyArrayGrow1(Object array, Class newArrayComponentType) {
if (array != null) {
int arrayLength = Array.getLength(array); //获得数组的长度,array不是数组将报异常
Object newArray = Array.newInstance(array.getClass().getComponentType(), arrayLength + 1);//根据类型创建一个数组
// getComponentType() --object representing the component type of an array, or null if the type is not an array 
     System.arraycopy(array, 0, newArray, 0, arrayLength); //复制数组
return newArray;
}
return Array.newInstance(newArrayComponentType, 1);
}


 给数组指定位置上设定值

  

        String[] joinedArray = (String[]) Array.newInstance(String.class, 10);
Array.set(joinedArray, 0, "a");
Array.set(joinedArray, 1, "b");
Array.set(joinedArray, 2, "c");
Array.set(joinedArray, 3, "d");
Array.set(joinedArray, 4, "e");
Array.set(joinedArray, 5, "f");
Array.set(joinedArray, 6, "g");
Array.set(joinedArray, 7, "h");
Array.set(joinedArray, 8, "i");
Array.set(joinedArray, 9, "j");
for (int i = 0; i < joinedArray.length; i++) {
System.out.println(joinedArray[i]);
}

从原来数组中返回一个子集
   

        int newSize = endIndexExclusive - startIndexInclusive; //开始和结束节点
Class type = array.getClass().getComponentType(); //数组包含的类型
if (newSize <= 0) {
return (Object[]) Array.newInstance(type, 0);
}
Object[] subarray = (Object[]) Array.newInstance(type, newSize);//创建新数组
System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);//数组复制


 

posted on 2012-01-10 10:43  neau火车  阅读(126)  评论(0编辑  收藏  举报

导航