1. 程式人生 > >Java陣列擴容演算法及Java對它的應用

Java陣列擴容演算法及Java對它的應用

1 public class Arrays { 2 /** 3 * @param original: the array to be copied 4 * @param newLength: the length of the copy to be returned 5 * @return a copy of the original array, truncated or padded with zeros 6 * to obtain the specified length 7 */ 8 public static
int[] copyOf(int[] original, int newLength) { 9 int[] copy = new int[newLength]; 10 System.arraycopy(original, 0, copy, 0, 11 Math.min(original.length, newLength)); 12 return copy; 13 } 14 /** 15 * @param original the array from which a range is to be copied
16 * @param from the initial index of the range to be copied, inclusive 17 * @param to the final index of the range to be copied, exclusive. 18 * (This index may lie outside the array.) 19 * @return a new array containing the specified range from the original array, 20 * truncated or padded with zeros to obtain the required length
21 */ 22 public static int[] copyOfRange(int[] original, int from, int to) { 23 int newLength = to - from; 24 if (newLength < 0) 25 throw new IllegalArgumentException(from + " > " + to); 26 int[] copy = new int[newLength]; 27 System.arraycopy(original, from, copy, 0, 28 Math.min(original.length - from, newLength)); 29 return copy; 30 } 31 }