java 實現重定義數組類似於VB的ReDim

碼農一個,直接上代碼:  
//param objArr   the expanded object of Array.
         //param  newLength  the length of the new Array  
  public static Object getNewArr(Object objArr, int newLength) {
if (!objArr.getClass().isArray()) {//判斷類型
return null;
}
// get the array's componentType
Class componentType = objArr.getClass().getComponentType();//獲得類型
//get a newInstance of a Array object
 
Object newArray = Array.newInstance(componentType, newLength);//新建數組對象
               //copy the array 
System.arraycopy(objArr, 0, newArray, 0, Array.getLength(objArr));//把原數組數據copy到新建數組中,其中newLength要大於元objArr的length,否則此句報錯
return newArray;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章