JAVA 가 변 길이 배열 만 들 기

1221 단어 자바
자바 고전 프로 그래 밍 300 예 중 하 나 는 재 미 있 는 기록 이 라 고 생각 합 니 다.
/**
 *       
 */
public class UsefulArray {
    public static Object increaseArray(Object array) {
        Class> clazz = array.getClass();//        Class  
        if (clazz.isArray()) {//         
            Class> componentType = clazz.getComponentType();//         
            int length = Array.getLength(array);//          
            Object newArray = Array.newInstance(componentType, length + 5);//    
            System.arraycopy(array, 0, newArray, 0, length);//            
            return newArray;//      
        }
        return null;//             
    }
    public static void main(String[] args) {
        int[] intArray = new int[10];
        System.out.println("         :" + intArray.length);
        Arrays.fill(intArray, 8);//            8
        System.out.println("       :");
        System.out.println(Arrays.toString(intArray));
        int[] newIntArray = (int[]) increaseArray(intArray);//       
        System.out.println("          :" + newIntArray.length);
        System.out.println("       :");
        System.out.println(Arrays.toString(newIntArray));
    }
}

좋은 웹페이지 즐겨찾기