1 public class ArrayList { 2 private final int MAXSIZE = 10; 3 private int[] arrays; 4 private int size = 0; 5 6 public ArrayList() { 7 arrays = new int[MAXSIZE]; 8 } 9 10 public ArrayList(int firstSize) { 11 arrays = new int[firstSize]; 12 } 13 14 /** 15 * 数组扩容 16 * 17 * @param oldSize 18 * 数组 19 * @param newSize 20 * 新容量 21 * @return 新数组 22 */ 23 public static int[] copy(int[] oldSize, int newSize) { 24 int[] copy = new int[newSize]; 25 System.out.println("扩容了"); 26 return copy; 27 } 28 29 /** 30 * 添加元素 31 * 32 * @param num 33 * 需要添加的元素 34 */ 35 public void add(int num) { 36 // 先判断是否要扩容 37 if (size == arrays.length) { 38 arrays = copy(arrays, size * 2); 39 } 40 arrays[size++] = num; 41 System.out.println("添加数据"+" "+num); 42 } 43 44 /** 45 * 获取指定位置的值 46 * 47 * @param i 48 * 指定位置 49 * @return 某个值 50 */ 51 public int get(int i) { 52 // 先判断是否溢出 53 if (size <= i) { 54 throw new IndexOutOfBoundsException("溢出"); 55 } 56 System.out.println("调用了get方法"); 57 return arrays[i]; 58 } 59 60 /** 61 * 设置指定位置的值 62 * 63 * @param i 64 * 指定位置 65 * @param num 66 * 新的值 67 * @return 某个值 68 */ 69 public int set(int i, int num) { 70 // 判断是否溢出 71 if (size <= i) { 72 throw new IndexOutOfBoundsException("溢出"); 73 } 74 arrays[i] = num; 75 return arrays[i]; 76 } 77 78 /** 79 * 获取数组的长度 80 * 81 * @return 数组长度 82 */ 83 public int size() { 84 return arrays.length; 85 } 86 87 public static void main(String[] arg) { 88 ArrayList list = new ArrayList(1); 89 list.add(1); 90 list.add(2); 91 list.add(3); 92 list.set(2, 5); 93 System.out.println("获取该值"+list.get(2)); 94 System.out.println("其长度为:"+list.size()); 95 } 96 }
运行结果:
添加数据 1
扩容了
添加数据 2
扩容了
添加数据 3
调用了get方法
获取该值5
其长度为:4
分析:ArrayList的基础实现不难,如果能考虑到溢出情况就更好了
原文:http://www.cnblogs.com/mjyung/p/6646534.html